为了实现循环大量行的最有效方法,我在Sheet3中创建了以下this answer启发的代码:
Sub Testing_Data()
Dim k As Long, S2 As Worksheet, VArray
Application.ScreenUpdating = False
Set S2 = ThisWorkbook.Sheets("Sheet2")
VArray = Range("A:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value
For k = 2 To UBound(VArray, 1)
S2.Cells(k, "B") = VArray(k, 1) / 100
S2.Cells(k, "C") = VArray(k, 1) * S2.Cells(k, "B")
Next
End Sub
运行代码后,发生运行时错误' 1004':应用程序定义或对象定义错误。如何解决?
答案 0 :(得分:1)
在单步执行代码后,错误出现在VArray =
行,这里有两件事:
Range("A:A"...
应该是Range("A"...
,因为您指定了一行而不是从整个工作表的顶部到底部选择整个列。Range
Range(FirstCell, LastCell)
。您的代码仅选择底部单元格,因此通过在范围引用的开头添加"A1",
,它将选择您需要的所有单元格。Sub Testing_Data()
Dim S2 As Worksheet, VArray() As Variant
Application.ScreenUpdating = False
Set S2 = ThisWorkbook.Sheets("Sheet2")
VArray = Range("A1", "A" & Cells(Rows.Count, "A").End(xlUp).Row)
For k = 2 To UBound(VArray)
S2.Cells(k, "B") = VArray(k, 1) / 100
S2.Cells(k, "C") = VArray(k, 1) * S2.Cells(k, "B")
Next
End Sub
答案 1 :(得分:1)
user1016274是正确的,您需要为您的范围和单元格添加S2
VArray = S2.Range("A:A" & S2.Cells(Rows.Count, "A").End(xlUp).Row).Value
或遵循他的建议:
With S2
VArray = .Range("A:A" & .Cells(Rows.Count, "A").End(xlUp).Row).Value
End With
非常有用。当你有多个法则时,它可以节省时间和空间。
另一个错误在于你的Range
。你必须定义用逗号分隔的2个单元格,在这里你定义A列和最后一行由&
分隔的单元格。试试这个:
VArray = Range(S2.Cells(1, 1), S2.Cells(Rows.Count, "A").End(xlUp))
修改强> 当我运行它时,它对我来说很好:
Sub Testing_Data()
Dim k As Long, S2 As Worksheet, VArray
Application.ScreenUpdating = False
Set S2 = ThisWorkbook.Sheets("Sheet2")
VArray = Range(S2.Cells(1, 1), S2.Cells(Rows.Count, "A").End(xlUp)).Value
For k = 2 To UBound(VArray, 1)
S2.Cells(k, "B") = VArray(k, 1) / 100
S2.Cells(k, "C") = VArray(k, 1) * S2.Cells(k, "B")
Next
End Sub
答案 2 :(得分:0)
VArray = Range("A:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value
不是引用Sheet2
,而是当前显示的工作表。使用
With S2
VArray = .Range("A1:A" & .Cells(Rows.Count, "A").End(xlUp).Row).Value
End With
注意来自" A:A"的变化到" A 1 :A"。 Range
对象需要以冒号分隔的起始单元格和结束单元格引用。
出于性能原因,您还应将以下语句放入With
块中。这样,对工作表的引用只会被搜索一次,而不是多次。