在Excel宏中创建CSE数组公式

时间:2013-01-22 21:17:09

标签: excel vba excel-vba excel-formula


在名为“Sheet2”的Excel工作表的单元格A1中,具有以下公式(CSE数组公式)

{=INDEX(Data1, MATCH(F26&G26,Data2&Data3,0),7)}
Data1 = Sheet1!$D$3:$J$604
Data2 = Sheet1!$D$3:$D$604
Data3 = Sheet1!$D$3:$E604

我想在VBA宏中重写这个,下面是我到目前为止所尝试的(是的,它给了我一个错误(错误:无法分配给数组)

Sub Button1_Click()

Dim var1(1 To 10) As Integer
Dim var2(1 To 10) As Integer

With Application.WorksheetFunction
   var1 = .Match((F26 And G26), (Worksheets("Sheet1").Range("D3:D604") And Worksheets("Sheet1").Range("E3:E604")), 0)
   var2 = .Index(Worksheets("Sheet1").Range("D3:J604"), var1, 7) 
   Range("A1").Value = var2
End With

End Sub

有任何建议/更正吗?

1 个答案:

答案 0 :(得分:0)

为什么要将var1var2定义为数组?

要连接字符串,请使用与公式相同的&运算符:(F26 & G26)
要连接范围,请使用Application.Union()方法:Application.Union(range1, range2)

我假设你从函数中想要返回你所在区域中与F26和G26中的值匹配的所有位置的数组

这将是我的尝试:

Option Explicit

Sub Button1_Click()
Dim Values()
Dim FindData
Dim Counter As Long
Dim DataPoints As Long
Dim ReturnData()
ReDim ReturnData(1)
DataPoints = 1

Values = Application.Union(Range("D3::D604"),Range("E3:E604"))
FindData = Range("F26").Value & Range("G26").Value

For Counter = LBound(Values) To UBound(Values)
    If findata = (Values(Counter, 1) & Values(Counter, 2)) Then
        ReDim Preserve ReturnData(DataPoints)
        ReturnData(DataPoints) = Counter
        DataPoints = DataPoints + 1
    End If
Next

Range("A1:A" & DataPoints) = ReturnData

End Sub