Excel VBA无法获得Vlookup属性
我知道这里有很多这样的问题,但是我看不出什么问题。
我有以下代码检查值是否在另一个工作簿中的列中。
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不起作用。 它作为一个excel公式很好。
我错过了什么?
使用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
我认为WorksheetFunction.Vlookup
的文档有问题。 在Excel 2007testing中,如果findsearchstring,则返回相应单元格的值。 如果你search一个完全匹配,你会得到可怕的错误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 <> "") ...
这似乎在Excel 2010中正常工作…
我build议你可能会得到一个VLOOKUP的错误,因为你已经jobNumber
作为string,尽pipe工作表/单元格“格式”,工作表中的工作号码可能存储为数值。
所以,问题在于“123”<> 123.testingjobNumber是否是数字,然后确保将正确的数据传递给函数。
If IsNumeric(jobNumber) Then Exists = Application.WorksheetFunction.VLookup(CLng(jobNumber), lookupRange, 1, False) Else: Exists = Application.WorksheetFunction.VLookup(jobNumber, lookupRange, 1, False) End If