我正在研究一个宏来遍历交错的字符串列并将它们连接起来。基本上,随着时间的推移,数据会被添加到列中,因此我需要将其设置为“面向未来的”#34;。目前它拿起了所有的H和I列,但只有J和K的第一个值。不知道为什么它适用于一半而不是另一半。我正在考虑使用我的.End(xldown),因为我习惯使用rows.end(xlup).count来循环遍历事物,但从来没有它是范围的一部分? 这是我的代码:
Sub Concatenation_for_the_nation()
Range("H2").End(xlDown).Select
For i = 1 To ActiveCell.Row
Range("H" & i).Select
StrStrONE = StrStrONE & " " & Selection
Next i
Cells(1, 1).Select
Range("I2").End(xlDown).Select
For j = 1 To ActiveCell.Row
Range("I" & j).Select
StrStrTWO = StrStrTWO & " " & Selection
Next j
Cells(1, 1).Select
Range("J2").End(xlDown).Select
For k = 1 To ActiveCell.Row
Range("J" & k).Select
StrStrTHREE = StrStrTHREE & " " & Selection
Next k
Cells(1, 1).Select
Range("K2").End(xlDown).Select
For l = 1 To ActiveCell.Row
Range("K" & l).Select
StrStrFOUR = StrStrFOUR & " " & Selection
Next l
Cells(1, 1).Select
Cells(21, 21) = StrStrONE & StrStrTWO & StrStrTHREE & StrStrFOUR
Cells(20, 20) = "Jeff"
MsgBox "steve the pirate"
End Sub
答案 0 :(得分:0)
您多次重复相同的逻辑,因此将其拉出到单独的Sub中是有意义的。
测试:
Sub Concatenation_for_the_nation()
Dim c As Range, s As String, sht As Worksheet
Set sht = ActiveSheet
For Each c In sht.Range("H1:K1")
s = s & ColumnString(c)
Next c
sht.Cells(21, 21).Value = s
sht.Cells(20, 20).Value = "Jeff"
MsgBox "arrrrr"
End Sub
Function ColumnString(cStart As Range, Optional sep As String = " ")
Dim rng As Range, c As Range, rv As String
Set rng = cStart.Parent.Range(cStart, _
cStart.Parent.Cells(Rows.Count, cStart.Column).End(xlUp))
For Each c In rng.Cells
rv = rv & sep & c.Value
Next c
ColumnString = rv
End Function