我有2个TextBox
控件,其中传递了条件1和条件2。该函数打开文件路径(destination1
)中提供的Excel文件,在Sheet2
中,vlookup必须采用col A,col B并将col C值返回textbox3
。
然而,我得到的错误是:
System.NullReferenceException未处理HResult = -2147467261 Message =对象引用未设置为对象的实例。
有没有一种简单的方法可以使用vlookup在VB.NET中搜索2个标准?
Public Sub lookValue()
Dim cit1 As String
Dim cit2 As String
Dim xlApp As Excel.Application
xlApp = New Excel.Application
Dim wb As Excel.Workbook = xlApp.Workbooks.Open(destination1)
Dim sht As Excel.Worksheet
Dim userange As Excel.Range
Dim lastrow As Long
Dim lastcolumn As Long
Dim startcell As Excel.Range
'Finding the dynamic table range in sheet lookup
sht = wb.Worksheets("Sheet2")
startcell = sht.Range("A1")
'Find Last Row and Column
lastrow = sht.Cells(sht.Rows.Count, startcell.Column).End(Excel.XlDirection.xlUp).Row
lastcolumn = sht.Cells(startcell.Row, sht.Columns.Count).End(Excel.XlDirection.xlToLeft).Column
'select range
userange = sht.Range(startcell, sht.Cells(lastrow, lastcolumn))
'Constraints from 2 textboxs given in userform
If TextBox1.Text <> "" And TextBox2.Text <> "" Then
cit1 = TextBox1.Text
cit2 = TextBox2.Text
'calling vlookup function by passing the lookup range from above, return value in col C if col A in excel sheet(lookup)
'has textbox 1.value & col B in excel sheet(lookup) has textbox2.value
TextBox3.Text = Two_Con_Vlookup(userange, 3, cit1, cit2)
'xlApp.WorksheetFunction.VLookup(raw, userange, 1, False))
End If
End Sub
Function Two_Con_Vlookup(Table_Range As Excel.Range, Return_Col As Long, Col1_Fnd As String, Col2_Fnd As String) As Object
Dim rCheck As Excel.Range, bFound As Boolean, lLoop As Long
Dim xlmath As Excel.WorksheetFunction
'On Error Resume Next
rCheck = Table_Range.Columns(1).Cells(1, 1)
With xlmath
For lLoop = 1 To .CountIf(Table_Range.Columns(1), Col1_Fnd)
rCheck = Table_Range.Columns(1).find(Col1_Fnd, rCheck, LookIn:=Excel.XlFindLookIn.xlFormulas, LookAt:=Excel.XlLookAt.xlWhole, SearchDirection:=Excel.XlSearchDirection.xlNext, SearcbOrder:=Excel.XlSearchOrder.xlByRows, MatchCase:=False)
If UCase(rCheck(1, 2)) = UCase(Col2_Fnd) Then
bFound = True
Exit For
End If
Next lLoop
End With
If bFound = True Then
Two_Con_Vlookup = rCheck(1, Return_Col)
Else
Two_Con_Vlookup = "Match Not Found"
End If
End Function
答案 0 :(得分:0)
您可以使用LINQ查询您需要使用vlookup的表以及vlookup表上的第二个查询,然后将两个查询的连接组合起来。为每个查询结果运行一个循环以输出您的Excel文件列。