如何连接单个单元格中的2列,即使一列是空的

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 

以上是我的代码。

我想连接列A和B到C列,用逗号间隔。 如果列A / B是空的,列C不应该有逗号,而只是值本身。

根据你的评论,你正在尝试做一些事情,如Excel公式=IF(A1="",IF(B1="","",B1),IF(B1="",A1,A1&" , "&B1)) ,我build议你使用下面的代码:

 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