INDEX - MATCH公式有错误?

时间:2015-09-04 00:17:06

标签: excel vba excel-vba indexing match

我有excel公式:

=INDEX('C:\Users\Desktop\[BOOK1.xlsx]Sheet1'!$J:$J,MATCH(A2,'C:\Users\Desktop\[BOOK1.xlsx]Sheet1'!$W:$W,0))

我在Excel vba中写这篇文章时遇到了麻烦,这是我到目前为止所做的:

Dim BOOK1 As Workbook
Dim bcklog1 As Worksheet

Set bcklog1 = BOOK1.Worksheets("backlog1")

Dim result As Variant
Dim match_formula As Variant

match_formula = "Match(Worksheets(1).Range("W:W"), 0)"
result = Evaluate(match_formula)
answer = Application.WorksheetFunction.Match(2, Worksheets(1).Range("W:W"), 0)
test = Application.WorksheetFunction.Index(Sheets("backlog1").Range("J:J"), result, 1)
index_formula = "Index(sales, result, )"
result2 = Evaluate(index_formula)

我无法获得任何结果,并且我的匹配公式会出现错误。我的方法是否正确?某些结果将包含错误,这是预期的。公式应该在另一个工作簿中查找值并匹配它们。

1 个答案:

答案 0 :(得分:0)

目标:在VBA中重现工作工作表公式

=INDEX('C:\Users\Desktop\[BOOK1.xlsx]Sheet1'!$J:$J, MATCH(A2, 'C:\Users\Desktop\[BOOK1.xlsx]Sheet1'!$W:$W,0))

这是使用多种方法的渐进式构造。检查VBE的立即窗口,查看debug.print输出。

'assumes that BOOK1 points to a workbook at this point
Dim bcklog1 As Worksheet
Set bcklog1 = BOOK1.Worksheets("backlog1")

Dim result As Variant, test As Variant
Dim frml As String, match_row As Long

'first we construct and evaluate the MATCH portion
frml = "match(A2, " & bcklog1.Range("W:W").Address(external:=True) & ", 0)"
Debug.Print frml
match_row = Evaluate(frml)
Debug.Print match_row

'next we build the remainder of the INDEX/MATCH around the match potion constructed earlier
frml = "index(" & bcklog1.Range("J:J").Address(external:=True) & ", " & frml & ")"
Debug.Print frml
result = Evaluate(frml)

'finally we abandon the Evaluate and use the match_row obtained earlier directly
test = Application.WorksheetFunction.Index(bcklog1.Range("J:J"), match_row, 1)
Debug.Print test

外部工作簿单元格范围地址作为字符串引入,Range.Address property带有可选的external:=True参数。这将返回格式正确的字符串,包括工作簿的完整路径,工作表名称(如果需要,带有单引号)和绝对单元格范围引用。

您可以通过使用等号前缀并将它们分配给目标单元格Range.Formula property,将这些公式字符串结构写回目标工作表。等号不是Application.Evaluate method的必要条件。

相关问题