2017-05-02 36 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

相关问题