0

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

我正在尝试将 XLookup-Formula 放入我的 vba 代码中。该代码引用了另一个工作表(“图表计划”,并且应该将“D”和“E”列(从第 2 行开始)中的值作为固定数组一直到“查找数组”的最后一行和“返回数组”。我希望这是可变的,因为“图表计划”根据我正在处理的内容使用不同的行号进行更新。然后该公式应该将值返回到活动工作表(列“J”)和遍历所有行(“B”作为 RC[-8] = 查找值给出)。我猜,问题是我真的不知道将数组放入公式的语法是什么,或者它是什么else entirly? 可能在 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
4

1 回答 1

0

我的 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
于 2021-04-08T11:16:15.880 回答