2016-03-08 29 views
-1

我有兩列正文在Excel中的cols A和B.發現山坳中的非空單元格並移動內容列B

我需要一個函數或VB代碼要經過每個單元中柱A,找到一個非空的單元格,例如A21,並將該單元格的內容移至B22。

然後繼續從A23開始搜索。

col A中帶有數據的行數可能是幾千條。

我該如何解決這個問題?

感謝您的幫助。

回答

0

試試這個:

Sub test() 

Dim lastrow As Integer 

lastrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row 

Range("A1").Select 

While ActiveCell.Row <= lastrow 

If ActiveCell.Value = "" Then 

ActiveCell.Offset(1, 0).Select 

Else 

ActiveCell.Offset(1, 1).Value = ActiveCell.Value 

ActiveCell.Offset(2, 0).Select 

End If 

Wend 

Range("A1").Select 

End Sub 

結果是這樣的:

enter image description here

+0

你也可以採取公式路線,並把它放在單元格B2中並填寫:'= IF(AND(A1 <>「」,B1 =「」),A1,「」)' –

0

您可以通過編寫VBA代碼

Sub moveColAToColB() 

    Dim currentSheet As Worksheet 
    Set currentSheet = Sheets("Sheet1") 

    Dim l As Long 


    With currentSheet 
     For l = 1 To .Rows.Count 
      If Not IsEmpty(.Cells(l, 1).Value) Then 
       .Cells(l, 2).Value = .Cells(l, 1).Value 

      End If 


     Next l 
    End With 

End Sub 

編輯解決這個問題:我還以爲你在你的描述有誤,但我不認爲你不能做的簡單的代碼的簡單修改...

Sub moveColAToColB() 

    Dim currentSheet As Worksheet 
    Set currentSheet = Sheets("Sheet1") 

    Dim l As Long 


    With currentSheet 
     For l = 1 To .Rows.Count 
      If Not IsEmpty(.Cells(l, 1).Value) Then 
       .Cells(l + 1, 2).Value = .Cells(l, 1).Value 
       l = l + 1 
      End If 


     Next l 
    End With 

End Sub 
+0

對不起,Luboš蘇克,你的代碼移動一切從山坳A到B.這不是我的算法描述了。不過謝謝你的回覆。 – ioio

+0

@ioio現在試着看... –

+0

Luboš,感謝您的努力。這現在也起作用。 – ioio

0

見代碼:

Sub MoveCellsFromColATOColB() 

    For x = 21 To ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row ' here is the start range declared also used range 

    Cells(x + 1, "B").Value = Cells(x, "A").Value 

    Next x 

End Sub 

結果:
enter image description here

問候

丹尼爾

+0

嗨丹尼爾,你的代碼接近解決方案,但你有效地將A2移動到B3,這不是我正在尋找的。我需要將A1移動到B2,但將A2留在原地。然後繼續在列A中搜索,直到它遇到A4中的文本,將其移至B5,依此類推。 – ioio

+0

哦!我錯過了什麼? –

0

考慮:

Sub MoveData() 
    Dim K As Long, nA As Long 
    Dim i As Long 

    nA = Cells(Rows.Count, "A").End(xlUp).Row 
    K = 22 

    For i = 1 To nA 
     If Cells(i, "A").Value <> "" Then 
      Cells(K, "B").Value = Cells(i, "A").Value 
      K = K + 1 
     End If 
    Next i 
End Sub 

例如:

enter image description here

+0

好的工作Gary我現在明白了= ) 我誤解了這一點哈哈。 –

相關問題