0

我觉得这是一件非常简单的事情,但我一直在谷歌搜索和试验一段时间,似乎空手而归,猜测是我在搜索错误的术语/单词。无论如何,让我解释一下。

例如 :

此代码:运行时错误“13”类型不匹配

Dim ws, sh As Worksheet

Set ws = Worksheets("Sheet1")

Set sh = Worksheets("Sheet2")
 
Dim Ctr1, Ctr2, Result As Range
 
Set Ctr1 = ws.Range("A2:A100")

Set Ctr2 = ws.Range("B2:B100")

Set Result = ws.Range("C2:C100")
 

With sh 
    .Cells(2, 7).Value = WorksheetFunction.XLookup( _
    .Cells(2, 5) & .Cells(2, 6), Ctr1 & Ctr2, Result, 0)
       
End With

 
End Sub    
4

1 回答 1

1

从范围地址创建 XLOOKUP 参数。

Sub Macro1()

    Dim ws As Worksheet, sh As Worksheet
    Set ws = Worksheets("Sheet1")
    
    Dim Ctr1, Ctr2, Result As Range
    Set Ctr1 = ws.Range("A2:A100")
    Set Ctr2 = ws.Range("B2:B100")
    Set Result = ws.Range("C2:C100")
    
    '  XLOOKUP parameters
    Dim p(3) As String, i As Long, w As String
    w = "'" & ws.Name & "'!"
    p(1) = w & Ctr1.Address(0, 0) & "&" & _
           w & Ctr2.Address(0, 0)
    p(2) = w & Result.Address(0, 0)
    p(3) = 0
    
    Set sh = Worksheets("Sheet2")
    With sh
        For i = 2 To 2
            p(0) = .Cells(i, 5).Address(0, 0) & "&" & .Cells(i, 6).Address(0, 0)
            .Cells(i, 7).Formula = "=XLOOKUP(" & Join(p, ",") & ")"
        Next
    End With
    
End Sub
于 2021-12-15T13:39:05.557 回答