我需要使用基于行值的幾列中的值。考慮到可能有幾千行并且值被多次使用,創建變體矩陣陣列并將所有列存盤在該陣列中,然后從該陣列中搜索和部署值,或者為每列創建一個陣列,是不是更好更快?
示例:我們有以下資料:

如果此人在 2013 年 1 月 1 日之前加入,我想從權益中扣除到期金額。宣告一個變體陣列是否更好
Dim matrix() as Variant
Dim ws as Worksheet
Dim cols(4) as String: cols(0) = "A': cols(1) = "B": cols(2) = "C": cols(3) = "D"
Dim i as Integer
Dim b as Integer: b = 2 'beginning row
Dim j as Integer: j = 4 'number of lines
Set ws = Worksheets("Sheet1")
For i = 0 to UBound(cols)
matrix(i) = Range(cols(i) & b & ":" & cols(i) & (b j)).value2
End if
要么
宣告單獨的四個陣列,例如
Dim arr1() as String
Dim arr2() as Date
Dim arr3() as Integer
Dim arr4() as Integer
當然,我也可以通過直接參考單元格來直接使用單元格中的資料,但是當我多次使用這個多千行資料時,將它們存盤在陣列中更有意義。
uj5u.com熱心網友回復:
如果有很多列,一次將所有資料讀入單個矩陣可能會明顯更快。Excel 和 VBA 之間的每次資料傳輸都會產生很大的開銷。較大的資料傳輸并不比小資料傳輸慢多少,但許多資料傳輸比單次傳輸慢很多。
這是一個很好的細節來源:
作業表單元格和 VBA 變數之間的資料傳輸是一項昂貴的操作,應盡量減少。您可以通過將資料陣列傳遞到作業表來顯著提高 Excel 應用程式的性能,反之亦然,在單個操作中而不是一次一個單元格中。如果您需要對 VBA 中的資料進行大量計算,則應將作業表中的所有值傳輸到陣列中,對陣列進行計算,然后可能將陣列寫回作業表。這將資料在作業表和 VBA 之間傳輸的次數保持在最低限度。將一個包含 100 個值的陣列傳輸到作業表比一次傳輸 100 個專案要高效得多。
http://www.cpearson.com/excel/ArraysAndRanges.aspx
uj5u.com熱心網友回復:
將范圍復制到陣列,反之亦然
Option Explicit
Sub DeductDue()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
' Reference the data (no headers) range ('rg').
Dim rg As Range
With ws.Range("A1").CurrentRegion
Set rg = .Resize(.Rows.Count - 1).Offset(1)
End With
' Write the values from columns 2-4 ('Date' to 'Due') to an array ('sData').
Dim sData As Variant: sData = rg.Columns(2).Resize(, 3).Value
' Wrtie the values from column 6 ('Equity') column to an array ('dData').
Dim dData As Variant: dData = rg.Columns(6).Value
' Loop through the rows of the arrays and calculate...
Dim r As Long
For r = 1 To rg.Rows.Count
If Year(sData(r, 1)) < 2013 Then
dData(r, 1) = dData(r, 1) - sData(r, 3)
End If
Next r
' Write the result to a column range, e.g.:
rg.Columns(6).Value = dData ' overwrite Equity with the deducted values
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/433526.html
