gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:32:24 25 4
gpt4 key购买 nike

我试图在宏中连续使用两个 VLookUp。该宏对 A 列和 C 列中的 ID 进行计数,在另一个表(同一工作表,范围从 F 列到 M -> F = ID,H = ID 描述)中搜索 ID 描述,并继续此搜索,直到达到计数为止将它们插入到 B 列和 D 列中。

不幸的是,我得到了

run time error 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

最佳答案

尝试将Integer替换为Long,然后重试。在 VBA 中,整数

-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") 时,请确保每次输入点 . 时,子项都是 的真正子项>与父级。在您的情况下 .Application 不是 Worksheets()
  • 的子项
  • 不要使用Integer,而是使用Long

关于VBA:为什么我不能连续使用两个 VLookUp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47869421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com