我同意@chris neilsen 的观点,但是...我刚刚意识到您可以实现Array 3rd 维度,例如可以保存颜色属性。
我检查过了。即使在少量数据上,它也比解决此问题的标准方法更快!
让我们在示例代码中展示它:(工作表结构)在第一行是标题,在第一列我们得到产品的 ID。
所以首先我们需要用单元格值和颜色属性声明和构建我们的Array(称为zakres)。
Sub main1()
Dim lastRow As Long
Dim lastCol As Long
Dim ws As Worksheet
Dim comper As Range
Dim j1 As Long
Dim i As Long
Dim zakres As Variant 'our 3 dimension Array
Set ws = Sheet1 'set your worksheet
With ws
lastRow = .Cells(Rows.Count, 1).End(xlUp).Row
lastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
ReDim zakres(1 To lastRow, 1 To lastCol, 1 To 2)
For i = 1 To lastRow
For j1 = 1 To lastCol
zakres(i, j1, 1) = .Cells(i, j1) 'cells value
zakres(i, j1, 2) = .Cells(i, j1).Interior.ColorIndex 'cells color property
Next
Next
毕竟我们想在那张桌子上做所有事情 - 我的意思是数组 zakres - 只需使用双循环(行和列)将所有值粘贴到您的工作表中
For i = 1 To lastRow
For j1 = 1 To lastCol
.Cells(i, j1) = zakres(i, j1, 1)
.Cells(i, j1).Interior.Color = zakres(i, j1, 2)
Next
Next
我对我的代码进行了修改,它只使用了单元格的 1 个属性 - 颜色属性 - 这种方法大大加快了我的代码速度。
附言。如果您不想用空单元格填充Array,只需在循环中创建条件函数,这将跳过空单元的迭代。它还有助于和加速宏。
If .Cells(i, j1) <> "" Then
zakres(i, j1, 1) = .Cells(i, j1)
zakres(i, j1, 2) = .Cells(i, j1).Interior.ColorIndex
End If
我希望它会帮助别人:)