当您尝试复制不相邻的单元格或范围选择时,例如同一列(A1、A3、A5)中的多个不相邻的行,就会出现第一个错误。这是因为 Excel 将范围“滑动”在一起并将它们粘贴为单个矩形。您的可见特殊单元格不相邻,因此无法作为单个范围进行复制。
看起来 Excel 正在循环遍历范围内的所有单元格,而不仅仅是可见的单元格。您的 debug.print 返回的行数不仅仅是可见的行数。
我会采取不同的方法通过使用数组来解决您的问题,与工作表相比,VBA 能够非常快速地循环遍历。
Using this approach, I was able to copy 9k rows with 10 columns based on the value of the first column from a sample size of 190k in 4.55 seconds:
EDIT:我对数组进行了一些修改,使用以下命令将基于第一列从初始 190k 行复制 9k 行的时间缩短至 0.45 秒:
Option Explicit
Sub update_column()
Dim lr1 As Long, lr2 As Long, i As Long, j As Long, count As Long, oc_count As Long
Dim arr As Variant, out_arr As Variant
Dim start_time As Double, seconds_elapsed As Double
Dim find_string As String
start_time = Timer
' change accordingly
find_string = "looking_for"
With Sheets("Sheet1")
' your target column in which you're trying to find your string
lr1 = .Cells(Rows.count, "A").End(xlUp).Row
lr2 = 1
' all of your data - change accordingly
arr = .Range("A1:J" & lr1)
' get number of features matching criteria to determine array size
oc_count = 0
For i = 1 To UBound(arr, 1)
If arr(i, 1) = find_string Then
oc_count = oc_count + 1
End If
Next
' redim array
ReDim out_arr(oc_count, 9)
' write all occurrences to new array
count = 0
For i = 1 To UBound(arr, 1)
If arr(i, 1) = find_string Then
For j = 1 To 10:
out_arr(count, j - 1) = arr(i, j)
Next j
count = count + 1
End If
Next
' write array to your target sheet, change sheet name and range accordingly
Sheets("Sheet2").Range("A1:J" & (oc_count + 1)) = out_arr
End With
seconds_elapsed = Round(Timer - start_time, 2)
Debug.Print (seconds_elapsed)
End Sub
它不是超级干净,可能需要进行一些改进,但如果速度很重要(通常看起来很重要),那么这应该可以很好地满足您的要求。