我建议放弃.Select
XL VBA 编程的方法,转而支持直接寻址,这样不会让你陷入错误。
Sub Concat()
Dim i As Long, lRow As Long
With Sheets("Sheet1")
lRow = .Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lRow
Sheets("Sheet2").Cells(i, 1) = .Cells(i, 1) & .Cells(i, 2)
Next i
End With
End Sub
注意前缀和.的句点(又名 . 或句号) 。这些告诉 .Cells 和 .Range 它们属于块中引用的工作表;在这个例子中是..Cells
.Range
With ... End With
Sheets("Sheet1")
如果你有很多行要串在一起,你最好从 Sheet1 创建一个值数组并在内存中处理连接。拆分连接的值并将它们返回给 Sheet2。
Sub concat2()
Dim c As Long, rws As Long, vCOLab As Variant
With Sheets("Sheet1")
rws = .Range("A2:A" & .Cells(Rows.Count, 1).End(xlUp).Row).Rows.Count
vCOLab = .Range("A2").Resize(rws, 3)
For c = LBound(vCOLab, 1) To UBound(vCOLab, 1)
'Debug.Print vCOLab(c, 1) & vCOLab(c, 2)
vCOLab(c, 3) = vCOLab(c, 1) & vCOLab(c, 2)
Next c
End With
Sheets("Sheet2").Range("A2").Resize(rws, 1) = Application.Index(vCOLab, , 3)
End Sub
与工作表交互时,批量操作每次都会跳一个循环;唯一的问题是多少。