VBA:为什么我不能连续使用两个VLookUps?

问题描述 投票:3回答:1

我想在我的宏中连续使用两个VLookUps。宏计算A列和C列中的ID,在另一个表中搜索ID描述(相同的表和范围从列F到M - > F = ID,H = ID描述)并继续此搜索,直到达到计数并且将它们插入B列和D列。

不幸的是,我得到了一个

运行时错误1004

当使用第二个VLookUp时。第一个工作正常,它与第一个完全一样,我只是指不同的细胞。

我想要实现的图片参考:

enter image description here

有谁知道是什么原因引起这个问题?

Dim i As Integer
Dim shA As Worksheet
Set shA = Worksheets(Format(Date, "dd.mm.yyyy"))
With shA

 For i = 4 To .Range("A4", .Range("A4").End(xlDown)).Rows.Count + 3
        .Cells(i, 2) = .Application.WorksheetFunction.VLookup(.Cells(i, 1), .Range("F:M"), 3, False)
 Next i 

 For i = 4 To .Range("C4", .Range("C4").End(xlDown)).Rows.Count + 3
        .Cells(i, 4) = .Application.WorksheetFunction.VLookup(.Cells(i, 3), .Range("F:M"), 3, False)
 Next i

End With
excel vba excel-vba
1个回答
3
投票

尝试用Integer替换Long并再试一次。在VBA中Integer

从-2 ^ 15到2 ^ 15-1或

从-32768到32767

因此,如果您在Excel中使用它并且它引用超出此范围的数字,则会出现错误。通常,您还有其他一些错误。尝试这一点,并确保选择了正确的ActiveSheet(我已经轻松完成了,你可以稍后更改):

Public Sub TestMe()

    Dim i As Long

    Dim shA As Worksheet
    Set shA = ActiveSheet

    With shA
        For i = 4 To .Range("A4", .Range("A4").End(xlDown)).Rows.Count + 3
            .Cells(i, 2) = Application.VLookup(.Cells(i, 1), .Range("F:M"), 3, False)
        Next i
        For i = 4 To .Range("C4", .Range("C4").End(xlDown)).Rows.Count + 3
            .Cells(i, 4) = Application.VLookup(.Cells(i, 3), .Range("F:M"), 3, False)
        Next i
    End With
End Sub

因此,一般来说:

  • 不要使用On Error Resume Next,因为它有点难。
  • 当你使用With Worksheets("someName"),然后确保每次你点一个点.,孩子是with-Parent真正的孩子。在你的情况下,.Application不是Worksheets()的孩子
  • 不要使用Integer,但Long
© www.soinside.com 2019 - 2024. All rights reserved.