简体   繁体   English

VBA中的Excel 2016 Vlookup函数

[英]Excel 2016 Vlookup Function in VBA

I need some help with Excel's Vlookup function. 我需要有关Excel的Vlookup函数的帮助。 I have 2 worksheets. 我有2个工作表。 On the first there's a Company Code, on the second I need to find values based on the company code. 第一个是公司代码,第二个是我需要根据公司代码查找值。 The relevant code is: 相关代码为:

Dim Compcode, AUC, OB As String
Dim WS1, WS2 As Worksheet
Set WS1 = ThisWorkbook.Worksheets("Main Sheet")
Set WS2 = ThisWorkbook.Worksheets("Data")
Compcode = WS1.Cells(2, 1).Value 'Company code WS1 A2

AUC = Application.WorksheetFunction.VLookup(Compcode, WS2.Range("A2:C30"), 2, False)
OB = Application.WorksheetFunction.VLookup(Compcode, WS2.Range("A2:C30"), 3, False)

I've tried to modify the Dim for each of the variables and the Vlookup function itself, but I always get to the same error message: 我试图修改每个变量的Dim和Vlookup函数本身,但是我总是得到相同的错误消息:

Run-time error '438': Object doesn't support this property or method 运行时错误“ 438”:对象不支持此属性或方法

WorksheetFunction.Vlookup is very volatile to the inputs and can throw runtime errors easily, as you've encountered. 正如您所遇到的那样, WorksheetFunction.Vlookup对于输入非常不稳定,并且可以轻松引发运行时错误。

Your issue could be one of a number of things but my suggested solution would be to just use Find instead: 您的问题可能是很多事情之一,但我建议的解决方案是仅使用Find代替:

Sub test()
    Dim Compcode As Variant, AUC As Variant, OB As Variant
    Dim WS1 As Worksheet, WS2 As Worksheet

    Set WS1 = ThisWorkbook.Worksheets("Main Sheet")
    Set WS2 = ThisWorkbook.Worksheets("Data")
    Compcode = WS1.Cells(2, 1).Value 'Company code WS1 A2

    Dim rng As Range
    Set rng = WS2.Range("A2:C30").Find(Compcode, , , xlWhole)

    If Not rng Is Nothing Then
        AUC = rng.Offset(0, 1).Value
        OB = rng.Offset(0, 2).Value
    End If
End Sub

The problem can be in many places. 问题可能出在很多地方。 Anyhow obviously, VLOOKUP is a bit picky on numbers and strings, thus the Compcode should be a Variant 无论如何,显然VLOOKUP对数字和字符串有点挑剔,因此Compcode应该是Variant

Something like this would work out: 这样的事情会解决:

Option Explicit

Public Sub TestMe()

    Dim Compcode        As Variant
    Dim AUC             As String
    Dim OB              As String

    Dim WS1             As Worksheet
    Dim WS2             As Worksheet

    Set WS1 = ThisWorkbook.Worksheets("Main Sheet")
    Set WS2 = ThisWorkbook.Worksheets("Data")

    Compcode = WS1.Cells(2, 1).Value

    Dim rngRange As Range

    Set rngRange = WS2.Range("A2:C30")

    AUC = Application.WorksheetFunction.VLookup(Compcode, rngRange, 2, False)
    OB = Application.WorksheetFunction.VLookup(Compcode, rngRange, 3, False)

End Sub

You should declare explicitly every variable, this is not c++/c to declare them with a comma and to hope that the VBEditor would understand. 您应该显式声明每个变量,而不是c++/c而不是用逗号声明它们并希望VBEditor能够理解。

I have also changed the formula to a range. 我也将公式更改为一定范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM