匹配函数循环通过变量字符串与偏移对应的值

时间:2013-11-05 16:05:45

标签: excel function vba match worksheet

我试图在一张纸上循环浏览客户名称(sheet2),在sheet1中的第J列中取相应的值,然后在原始工作表上的客户旁边粘贴。

这是我的代码:

For i = 0 To 9

Dim rowi As Long

rowi = Application.WorksheetFunction.Match((Worksheets("Sheet2").Cells(5 + i, 4)), Worksheets("Sheet1").Range("B:B"), 0)
Crystali = Cells(rowi, 10)
Sheets("Sheet2").Activate
Worksheets("Sheet2").Cells(5 + i, 7) = Crystali
Next i

有人可以帮我解决吗?我一直收到错误“无法获取Worksheetfunction类的匹配属性”

提前致谢。

1 个答案:

答案 0 :(得分:0)

这里简短的示例如何使用'Match()'函数而不使用像Tim建议的'workheet-function'部分。调用Match函数后,只需使用'IsError()'检查结果。

Option Explicit

Public Sub test()
    Dim row_index As Long
    Dim match_result As Variant
    Dim lookup_value As Variant
    Dim lookup_array As Variant

    Set lookup_array = Range("Sheet1!B:B")

    Const FIRST_ROW As Byte = 5
    Const LAST_ROW As Byte = 9

    For row_index = FIRST_ROW To LAST_ROW

        Set lookup_value = Range("Sheet2!D" & row_index)
        match_result = Application.Match(lookup_value, lookup_array, 0)

        If Not IsError(match_result) Then
            ' copy data only if Match function found something
            Range("Sheet2!G" & row_index) = Range("Sheet1!J" & match_result)
        End If

    Next row_index
End Sub