[英]Excel VBA filter to Array with criteria
I am trying to filter table data into an array with criteria from a separate column within that table I can achieve this on a worksheet with a simple formula which creates a spilled array.我正在尝试将表数据过滤到具有来自该表中单独列的条件的数组中,我可以在工作表上使用创建溢出数组的简单公式来实现这一点。
=FILTER(tblMain[Name],tblMain[At Work]=1)
The code I am trying does not work?我正在尝试的代码不起作用?
Sub myArraySub()
Dim myTable As ListObject
Dim myArray1 As Variant
Dim myArray2 As Variant
Dim myArray3 As Variant
'Set path for Table variable
Set myTable = ActiveWorkbook.Worksheets("Main").ListObjects("tblMain")
'Create Array
myArray1 = Application.Transpose(myTable.ListColumns("Name").DataBodyRange.Value)
myArray2 = Application.Transpose(myTable.ListColumns("At Work").DataBodyRange.Value)
myArray3 = Application.Filter(myArray1, myArray2 = 1)
End Sub
I am getting errors and going in circles trying to solve what should be a simple problem.我遇到错误并绕着圈子试图解决应该是一个简单的问题。 I will then ultimately use the array to test other tables if the Name appears in the array.
如果名称出现在数组中,我最终将使用该数组来测试其他表。 TIA
TIA
It's not possible to do this with this approach, mainly because in VBA you can't compare an array directly to a single value and return an array.使用这种方法是不可能做到这一点的,主要是因为在 VBA 中,您不能将数组直接与单个值进行比较并返回一个数组。
What you could do is use Evaluate with the formula you already have.您可以做的是将 Evaluate 与您已有的公式一起使用。
Sub myArraySub()
Dim myArray1 As Variant
myArray1 = Evaluate("=FILTER(tblMain[Name],tblMain[At Work]=1)")
End Sub
In case you don't can't use very creative answer you got from @Norie in this thread, your question was also answered here extensively.如果您不能在此线程中使用从@Norie 获得的非常有创意的答案,您的问题也在这里得到了广泛的回答。 But reading through all the solutions there I wondered whether they were worth the effort.
但是通读那里的所有解决方案,我想知道它们是否值得付出努力。 So, here is a more plodding way of achieving the same result.
因此,这是实现相同结果的更繁琐的方法。 It may well be your best bet if the number of rows in your table isn't very large.
如果表中的行数不是很大,这可能是您最好的选择。
Function MyArray() As Variant
Dim Fun As Variant ' function return array
Dim Arr As Variant ' working copy of entire table
Dim Rs As Long ' loop counter: Arr (Source) rows
Dim Rt As Long ' loop counter: Fun (Target) rows
Dim C As Long ' loop counter: columns
Arr = ActiveWorkbook.Worksheets("Main").ListObjects("tblMain").DataBodyRange.Value
ReDim Fun(1 To UBound(Arr, 2), 1 To UBound(Arr))
For Rs = 1 To UBound(Arr)
If Arr(Rs, 2) = 1 Then
Rt = Rt + 1
For C = 1 To UBound(Arr, 2)
Fun(C, Rt) = Arr(Rs, C)
Next C
End If
Next Rs
ReDim Preserve Fun(1 To UBound(Fun), 1 To Rt)
MyArray = Application.Transpose(Fun)
End Function
Use the little procedure below for testing.使用下面的小程序进行测试。
Sub Test_MyArray()
Dim Arr As Variant
Dim R As Long
Dim C As Long
Arr = MyArray
For R = 1 To UBound(Arr)
For C = 1 To UBound(Arr, 2)
Debug.Print Arr(R, C),
Next C
Debug.Print
Next R
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.