Excel vba无法获取Vlookup属性

时间:2013-03-22 15:54:52

标签: excel excel-vba vba

我知道这里有很多这些问题,但我看不出有什么问题。

我有以下代码检查某个值是否在另一个工作簿的列中。

Dim masterWbk As Workbook
Dim oWbk As Workbook
Dim RowCount As Integer
Dim LookupRange As Range
Dim Exists As Variant
Dim a As Integer
Dim i As Integer
Dim jobnumber As String

    RowCount = WorksheetFunction.CountA(Sheets("Sheet1").Range("A1").EntireColumn)

    masterWbk.Activate

Set LookupRange = masterWbk.Sheets("Sheet1").Range("C1:C100")

    a = 0

    For i = 0 To RowCount - 1

        jobnumber = oWbk.Sheets("Sheet1").Range("A2").Offset(i, 0).Value

      '  On Error GoTo ExistsError:

        Exists = Application.WorksheetFunction.VLookup(jobnumber, LookupRange, 1, False)

现在该值肯定在查找范围内并且格式相同但Vlookup不起作用。它作为一个优秀的公式很好。

我错过了什么?

3 个答案:

答案 0 :(得分:3)

使用find它看起来像这样 -

Dim masterWbk As Workbook
Dim oWbk As Workbook
Dim RowCount As Integer
Dim LookupRange As Range
Dim Exists As Variant
Dim a As Integer
Dim i As Integer
Dim jobnumber As String

    RowCount = WorksheetFunction.CountA(Sheets("Sheet1").Range("A1").EntireColumn)

    masterWbk.Activate

Set LookupRange = masterWbk.Sheets("Sheet1").Range("C1:C100")

  a = 0

  For i = 0 To RowCount - 1

  jobnumber = oWbk.Sheets("Sheet1").Range("A2").Offset(i, 0).Value
  If Trim(jobnumer) <> "" Then
    With lookuprange
        Set Rng = .Find(What:=jobnumber, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            Exists = 1
        Else
            Exist = 0
        End If
    End With
  End If

答案 1 :(得分:0)

我认为WorksheetFunction.Vlookup的文档存在问题。在我对Excel 2007的测试中,如果找到搜索字符串,则返回相应单元格的值。如果您搜索完全匹配,则会出现可怕的错误1004。

如果您想使用Vlookup,

...

Dim FoundText as String

...

FoundText=""

On Error Resume Next

FoundText=Application.WorksheetFunction.VLookup(jobnumber, LookupRange, 1, False)

On Error Goto 0

Exists= (FoundText <> "")

...

答案 2 :(得分:0)

这似乎在Excel 2010中运行良好......

我建议您使用VLOOKUP时可能会出错,因为您已将jobNumber标注为字符串,尽管工作表/单元格“格式化”,但工作表中的作业编号可能会存储为数值。

所以,问题在于“123”&lt;&gt; 123.测试jobNumber是否为数字,然后确保将正确类型的数据传递给函数。

If IsNumeric(jobNumber) Then
    Exists = Application.WorksheetFunction.VLookup(CLng(jobNumber), lookupRange, 1, False)
Else:
    Exists = Application.WorksheetFunction.VLookup(jobNumber, lookupRange, 1, False)
End If