簡體   English   中英

excel:索引並與vba匹配

[英]excel: index and match with vba

我在工作表的第一列中有以下公式:

=IFERROR(INDEX(Plan2!$A$1:$K$20;MATCH(Plan3!B2;Plan2!$B$1:$B$20;0);MATCH(Plan3!$A$1;Plan2!$A$1:$K$1;0));"")

在此處輸入圖片說明

而且它非常適合我的需求:通過匹配表頭來匹配結果,從而在Plan2(我的數據庫)上查找Plan3列B上的信息。

我想知道的是將其轉換為可以執行相同操作的VBA。 到目前為止,這是我嘗試過的:

Sub AlocSubs()

Dim i As Long
Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Sheets("Plan2")
Set ws2 = Sheets("Plan3")

For i = 2 To 20
    ws2.Cells(i, 1).Value = Application.WorksheetFunction.Index(ws1.Range("A1:K20"), .match(ws2.Range("B2"), ws1.Range("B1:B20"), 0), .match(ws2.Range("A1"), ws1.Range("A1:K1"), 0))
Next i

End Sub

當我嘗試運行時,收到消息:

編譯錯誤:引用無效。

我將這一行突出顯示:

Sub AlocSubs()

這是我第一次嘗試轉換公式在VBA中執行代碼,因此我真的不知道出了什么問題。

任何建議將不勝感激。

您使用了.match ,但是之前沒有With語句。 您也不要在公式中使用i 我想應該是這樣的:

With Application.WorksheetFunction
    For i = 2 To 20
        ws2.Cells(i, 1).Value = .Index(ws1.Range("A1:K20"), .Match(ws2.Range("B" & i), ws1.Range("B1:B20"), 0), .Match(ws2.Range("A1"), ws1.Range("A1:K1"), 0))
    Next i
End With

嘗試這個:

Sub AlocSubs()
    Dim i As Long
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim strFormula As String

    Set ws1 = Sheets("Plan2")
    Set ws2 = Sheets("Plan3")
    strFormula = "=IFERROR(INDEX(Plan2!$A$1:$K$20;MATCH(Plan3!B2;Plan2!$B$1:$B$20;0);MATCH(Plan3!$A$1;Plan2!$A$1:$K$1;0));"""")"

    With ws2
        With .Range(.Cells(2, 1), .Cells(20, 1))
            .Formula = strFormula
            .Value = .Value
        End With
    End With
End Sub

注意:我尚未測試您的公式。 代碼顯示了如何使用VBA顯示公式結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM