我有一个Excel文件如下:
A 1 E A, 1, E
B F B, F
C 2 G C, 2, G
我需要一个宏来生成结果,如第四列所示。最终,它将合并单元格并在每个值之间放置逗号。我的文件转到BX列,有时是CA,所以有很多列。任何帮助表示赞赏!我正在使用office 2007。 我有以下内容:
Sub Merge()
Dim outputText As String
Const delim = ","
On Error Resume Next
For Each cell In Selection
outputText = outputText & cell.Value & delim
Next cell
With Selection
.Clear
.Cells(1).Value = outputText
.Merge
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlCenter
.WrapText = True
End With
End Sub
但是当我在第二行执行此宏时,我得到以下输出:B ,, F而不是B,F
答案 0 :(得分:0)
一些小改动
Sub Merge()
Dim outputText As String, sep As String
Dim cell As Range, rw As Range
Const DELIM = ","
outputText = ""
sep = ""
For Each rw in ActiveSheet.Range("A1:CA3").Rows
For Each cell In rw.Cells
If Len(cell.Value) > 0 Then
outputText = outputText & sep & cell.Value
sep = DELIM
End If
Next cell
With rw
.Clear
.Cells(1).Value = outputText
.Merge
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlCenter
.WrapText = True
End With
Next rw
End Sub