我有一个非常大的电子表格,我想进行计算。为了加快速度,我想在vba中完成它们。我有一个vba的基本知识,所以开始我试图编写代码,只需复制A列中的单元格并将它们分配给一个数组然后将所有值粘贴回另一列D.我定义了numrows来获取数字行数下降,因为这将逐月变化。我想如果我可以让它工作,我可以从那里建立它 - 但不幸的是我不能让它工作。如果有人能告诉我我做错了什么,我真的很感激。
我尝试了很多这方面的变化 - 目前我收到错误运行时错误' 424'对象是必需的所以我认为数组是空的。
Option Explicit
Option Compare Text
Option Base 1
Sub Macro1()
Dim numRows As Long
Dim numCols As Integer
numCols = 1
Dim RowCounter As Long
Dim ColCounter As Integer
Dim SumCols() As Variant
numRows = Cells(Rows.Count, "A").End(xlUp).Row
ReDim SumCols(numRows, numCols)
Dim tempSumCols As Variant
tempSumCols = Range("A2", Cells(numRows, 1))
For RowCounter = 1 To numRows
For ColCounter = 1 To numCols
SumCols(RowCounter, ColCounter) = tempSumCols(RowCounter, ColCounter).Value
Next ColCounter
Next RowCounter
Range("D2", Cells(numRows, "D")) = SumCols
End Sub
答案 0 :(得分:2)
要修复代码,必须匹配两个数组中的numRows 因为你从A2开始 - 你的行索引需要增加
并且 - 从第二个数组中删除.Value
这应该可以 - 或者至少删除运行时错误:
Sub Macro1()
Dim numRows As Long
Dim numCols As Integer
numCols = 1
Dim RowCounter As Long
Dim ColCounter As Integer
Dim SumCols() As Variant
numRows = Range("A" & Rows.Count).End(xlUp).Row
ReDim SumCols(numRows, numCols)
Dim tempSumCols As Variant
' Increment number of rows to match numrows starting at A2
tempSumCols = Range("A2", Cells(numRows + 1, 1))
For RowCounter = 1 To numRows
For ColCounter = 1 To numCols
' Remove .Value from tempSumCols
SumCols(RowCounter, ColCounter) = tempSumCols(RowCounter, ColCounter)
Next ColCounter
Next RowCounter
Range("D2", Cells(numRows, "D")) = SumCols
End Sub
答案 1 :(得分:1)
从范围填充数组的最简单方法:
现在可以使用
遍历数组对于i = lBound(数组)到uBound(数组)
或
对于数组中的每个e
Sub Macro1() Dim SumCols As Variant Dim e As Variant SumCols = Range(Range("A2"), Range("A" & Rows.Count).End(xlUp)).Value For Each e In SumCols Next Range("D2").Resize(UBound(SumCols, 1), UBound(SumCols, 2)) = SumCols End Sub