数组变量下标超出范围

时间:2018-10-03 20:36:55

标签: vba excel-vba

我试图定义一个数组变量,但是在运行时总是遇到运行时错误9下标超出范围。谁能帮忙吗? 以下是我的代码

Dim wkbNPI As Workbook
Dim wksPT As Worksheet
Dim wksFU As Worksheet

Dim lrw As Long

Set wkbNPI = ActiveWorkbook
Set wksPT = Sheets("Packaging tracking")
Set wksFU = Sheets("FollowUpMaterial")

lrw = wksPT.Cells(Rows.Count, "AE").End(xlUp).row
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction

Dim PTarray As Variant
PTarray = wkbNPI.wksPT.Range("A7:AG" & lrw).Value

Dim i As Long, j As Long

For i = 7 To UBound(PTarray)
    If PTarray(i, 31) <> 0 Then
        PTarray(i, 32) = wf.IfError(wf.VLookup(PTarray(i, 31), wksFU.Range("B:R"), 13, False), "")                    'vlookup follow up material
        PTarray(i, 33) = wf.IfError(wf.VLookup(PTarray(i, 31), wksFU.Range("B:R"), 17, False), "")                      'vlookup follow up material effective out date
    End If
Next i

On Error Resume Next

End Sub

1 个答案:

答案 0 :(得分:1)

分别定义图纸对象和工作簿对象。

尝试这样。

Sub test()
Dim wkbNPI As Workbook
Dim wksPT As Worksheet
Dim wksFU As Worksheet

Dim lrw As Long

Set wkbNPI = ActiveWorkbook
Set wksPT = wkbNPI.Sheets("Packaging tracking") '<~~ set sheet with workbook
Set wksFU = wkbNPI.Sheets("FollowUpMaterial") '<~~ set sheet with workbook

lrw = wksPT.Cells(Rows.Count, "AE").End(xlUp).Row
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction

Dim PTarray As Variant
PTarray = wksPT.Range("A7:AG" & lrw) '< remove workbook

Dim i As Long, j As Long

For i = 7 To UBound(PTarray)
    If PTarray(i, 31) <> 0 Then
        PTarray(i, 32) = wf.IfError(wf.VLookup(PTarray(i, 31), wksFU.Range("B:R"), 13, False), "")                    'vlookup follow up material
        PTarray(i, 33) = wf.IfError(wf.VLookup(PTarray(i, 31), wksFU.Range("B:R"), 17, False), "")                      'vlookup follow up material effective out date
    End If
Next i

On Error Resume Next

End Sub