2012-02-21 127 views
1

我有一個棘手的情況。我有隻有標題的列A和列B包含文本。現在我想讓列B中的文本從列A開始。如果列A中有文本,則B將始終爲空。Excel VBA - 合併

A   B 
Title 1 
      Text 1 
      Text 2 
Title 2 
      Text 1 
      Text 2 

我怎麼能得到它,所以列B中的文本放在列A.範圍設置,直到找到一個完整的空行。 (A1到S1在單元格中沒有值=空行) 我在考慮合併單元格,但這可能並不整齊。

+0

[你嘗試過什麼?(http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2012-02-21 16:45:00

回答

1

是否這樣?這使用合併,並考慮到A和B都填滿了。

Sub Sample() 
    Dim ws As Worksheet 
    Dim LastRow As Long 

    Set ws = Sheets("Sheet5") 

    With ws 
     LastRow = .Range("B" & .Rows.Count).End(xlUp).Row 

     For i = 1 To LastRow 
      If Application.WorksheetFunction.CountA(.Range("A" & i & ":" & "B" & i)) = 1 And _ 
      Len(Trim(.Range("A" & i).Value)) = 0 Then 
       With .Range("A" & i & ":" & "B" & i) 
        .Merge 
       End With 
      End If 
     Next i 
    End With 
End Sub 

跟進

如果你不想合併和A將一直保持爲空時,有在B的值那麼我們可以從色柱B值移入柱A這樣

Sub Sample() 
    Dim ws As Worksheet 
    Dim LastRow As Long 

    Set ws = Sheets("Sheet5") 

    With ws 
     LastRow = .Range("B" & .Rows.Count).End(xlUp).Row 

     For i = 1 To LastRow 
      If Len(Trim(.Range("A" & i).Value)) = 0 Then 
       .Range("A" & i).Value = .Range("B" & i).Value 
       .Range("B" & i).ClearContents 
      End If 
     Next i 
    End With 
End Sub 
+0

所以LASTROW在B的第一行是完全空的? (A到S)你似乎合併了A和B,但是如果我想將值剪切/粘貼到A中,那會是怎樣呢? – CustomX 2012-02-21 16:25:51

+0

沒有lastrow是列B中非空的最後一行,用您最近的請求更新代碼。 – 2012-02-21 16:26:56

+0

你不想要「S」,因爲你打算從「B」而不是「S」移動價值。假設「S」直到第100行,「B」直到第15行,然後沒有點循環到100,因爲從B16到B100的單元將爲空。 – 2012-02-21 16:38:05