[英]Filter Array in Excel VBA
如何過濾多維數組?
我的代碼行不通,看起來也不整潔:
Option Explicit
Sub CalcE()
Dim TotalRows As Long
Dim myArray, myArray2 As Variant
Dim i, a As Integer
填充數組
TotalRows = Sheets("Data").Rows(Rows.Count).End(xlUp).Row
myArray = Sheets("Data").Range("A5:F" & TotalRows)
MsgBox "Array populated with " & UBound(myArray) & "entries."
將myArray條目過濾到myArray2中,但僅過濾第1、4和6列。
a = 0
For i = 0 To UBound(myArray)
If myArray(i, 1) > 1 Then
myArray2(a, 1) = myArray(i, 1)
myArray2(a, 2) = myArray(i, 4)
myArray2(a, 3) = myArray(i, 6)
a = a + 1
End If
Next i
MsgBox "Array populated now with " & UBound(myArray2) & "entries."
End Sub
我用谷歌搜索並發現Excel中的數組似乎是非常僵化的東西,不好用。 人們通常會放棄使用VBA數組,而使用自動篩選方法。 我為是否真的沒有一個好方法而煩惱。 擁有它真是太好了!
如果您只需要將第1、4和6列存儲到myArray2
,請嘗試一下...
Dim ws As Worksheet
Set ws = Sheets("Data")
TotalRows = ws.Rows(Rows.Count).End(xlUp).Row
myArray2 = Application.Index(ws.Cells, Evaluate("Row(5:" & TotalRows & ")"), Array(1, 4, 6))
或者您可以像這樣調整代碼...
Dim ws As Worksheet
Set ws = Sheets("Data")
Dim cnt As Long, j As Long
TotalRows = ws.Rows(Rows.Count).End(xlUp).Row
myArray = ws.Range("A5:F" & TotalRows).Value
cnt = Application.CountIf(ws.Range("A5:A" & TotalRows), ">1")
If cnt = 0 Then Exit Sub
ReDim myArray2(1 To cnt, 1 To 3)
For i = 1 To UBound(myArray, 1)
If myArray(i, 1) > 1 Then
j = j + 1
myArray2(j, 1) = myArray(i, 1)
myArray2(j, 2) = myArray(i, 4)
myArray2(j, 3) = myArray(i, 6)
End If
Next i
MsgBox UBound(myArray2, 1)
數組不是很靈活:特別是不容易調整大小(盡管您可以使用Redim Preserve
來調整大小)。
就個人而言,如果您想要可變數量的項目,或者想要在VBA中過濾項目,我會使用Collection。
首先定義一個具有表示2D數組列的屬性或字段的類模塊。 您應該給該類及其屬性賦予有意義的名稱和適當的數據類型,但是我不知道您的應用程序,因此我將使用:
Class Module "MyClass":
Public Col1 As Variant
Public Col4 As Variant
Public Col6 As Variant
然后,您可以創建一個Collection並將類的實例添加到它,如下所示:
Dim col As Collection
Set col = New Collection
For i = LBound(myArray, 1) To UBound(myArray, 1)
If myArray(i, 1) > 1 Then
Dim c As MyClass
Set c = New MyClass
c.Col1 = myArray(i, 1)
c.Col4 = myArray(i, 4)
c.Col6 = myArray(i, 6)
col.Add c
End If
Next I
然后,您可以進一步過濾它,例如:
Dim col2 As Collection
Set col2 = New Collection
For Each c In col
If c.Col1 = 5 Then
col2.Add c
End If
Next c
最后將其復制回2D數組,以便可以將其寫回到Excel工作表:
Dim myArray2() As Variant
Dim c As MyClass
ReDim myArray2(0 To col2.Count - 1, 0 To 6)
For i = 0 To col2.Count - 1
Set c = col2(i + 1) ' Collection indexes are 1-based
myArray2(i, 1) = c.Col1
myArray2(i, 4) = c.Col4
myArray2(i, 6) = c.Col6
Next i
您甚至可以編寫類模塊,它是MyClass
對象的強類型集合 ,如鏈接的博客文章中所述,是類模塊MyClassCollection
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.