2017-05-02 35 views
1
Sub ConcatColumns() 

    Do While ActiveCell <> "" 'Loops until the active cell is blank. 

     'The "&" must have a space on both sides or it will be 
     'treated as a variable type of long integer. 

     ActiveCell.Offset(0, 1).FormulaR1C1 = _ 
     ActiveCell.Offset(0, -1) & " , " & ActiveCell.Offset(0, 0) 

     ActiveCell.Offset(1, 0).Select 
    Loop 

End Sub 

以上是我擁有的代碼。如何連接單個單元格中的2列,即使一列爲空

我想將列A & B連接到列C中,並用逗號間隔。 如果列A/B是空的,列C不應該有逗號,而只是值本身。

+0

所以,你想創建一個類似於Excel公式'= IF東西(A1 =「」,IF(B1 =「」,「」,B1),IF(B1 =「」,A1,A1&「,」&B1))'? – YowE3K

+0

yeap。這就像那樣 – eqah12

回答

0

基於您的評論,你試圖做類似的Excel公式=IF(A1="",IF(B1="","",B1),IF(B1="",A1,A1&" , "&B1)),我建議你使用下面的代碼:

Sub ConcatColumns() 

    Do While ActiveCell.Value <> "" Or ActiveCell.Offset(0, -1).Value <> "" 
     With ActiveCell 
      ' IF(A1="" 
      If .Offset(0, -1).Value = "" Then 
       ' IF(B1="" 
       If .Value = "" Then 
        ' "" 
        .Offset(0, 1).Value = "" ' Shouldn't occur, but let's be safe 
       Else 
        ' B1 
        .Offset(0, 1).Value = .Value 
       End If 
      ' IF(B1="" 
      ElseIf .Value = "" Then 
       ' A1 
       .Offset(0, 1).Value = .Offset(0, -1).Value 
      Else 
       ' A1&" , "&B1 
       .Offset(0, 1).Value = .Offset(0, -1).Value & " , " & .Value 
      End If 
     End With 
     ActiveCell.Offset(1, 0).Select 
    Loop 
End Sub 
+0

謝謝你的幫助!有用 :) – eqah12

相關問題