在两个不同的工作表中使用 XLOOKUP 并具有可变数组范围(VBA 编码)

Using XLOOKUP in two different Sheets and having a variable array extent (VBA Coding)

你好,我对 VBA 编码和一般编码还很陌生,所以我希望你能快速回答我的问题。

我正在尝试将 XLookup-Formula 添加到我的 vba-Code 中。该代码引用了另一个 Sheet(“图表计划”,并且应该将“D”和“E”列(从第 2 行开始)中的值作为固定数组,一直到“查找”的最后一行array”和“return array”。我希望它是可变的,因为“图表计划”根据我正在处理的内容更新了不同的行号。然后公式应该 return the值到活动工作表(列“J”)并遍历所有行(“B”给出为 RC[-8] = 查找值)。 我想,问题是我真的不知道将数组赋给公式的语法是怎样的,还是完全是其他东西?可能混合使用 RC-Annotation 和 A1-Annotation?

谢谢。


Dim aEndKP As Variant
Dim aStartKP As Variant
Dim aCN As Variant

Sub ChartPlanScript()

Dim row As Long
Dim last_row As Long
Dim rng As Range
Dim ws As Worksheet

'Array End KP

LReKP = Sheets("Chart Plan").Cells(Rows.Count, "D").End(xlUp).row
aEndKP = Sheets("Chart Plan").Range("D2:D" & LReKP)

'Array Start KP

LRsKP = Sheets("Chart Plan").Cells(Rows.Count, "E").End(xlUp).row
aStartKP = Sheets("Chart Plan").Range("C2:C" & LRsKP)

'Array Chart Plan
 
LRCN = Sheets("Chart Plan").Cells(Rows.Count, "E").End(xlUp).row
aCN = Sheets("Chart Plan").Range("E2:E" & LRCN)
 
 
Set ws = Sheets(1)
ws.Activate

last_row = ws.Range("A5000").End(xlUp).row

For row = 2 To last_row
        If Range("A" & row).Value > 0 Then

         ws.Range("J" & row).Value = "=XLOOKUP(RC[-8],[aEndKP],[aCN],,1,1)"

        Else
       ws.Range("J" & row).Value = ""
    End If
Next row

End Sub

我的 Excel 版本没有 XLOOKUP,但这会使用 VLOOKUP

Option Explicit

Sub ChartPlanScript()

    Dim ws As Worksheet
    Dim i As Long, last_row As Long
    Dim sCN As String

    'Chart Plan
    With Sheets("Chart Plan")
        last_row = .Cells(Rows.Count, "D").End(xlUp).row
        sCN = "'Chart Plan'!" & .Range("D2:E" & last_row).Address
    End With
     
    Set ws = Sheets(1)
    ws.Activate
    last_row = ws.Range("A5000").End(xlUp).row

    For i = 2 To last_row
        If ws.Cells(i, "A") > 0 Then
            ws.Range("J" & i).Formula = "=VLOOKUP(B" & i & "," & sCN & ",2,0)"
        Else
            ws.Cells(i, "J") = ""
        End If
    Next
    MsgBox i - 1 & " rows processed"

End Sub