2016-11-24 20 views
0

我有2 TextBox控件,其中條件1和條件2通過。該函數打開文件路徑(destination1)和Sheet2中提供的Excel文件,該查找必須獲取col A,col B並將col C值返回至textbox3如何用excel數據做2條準則查詢

但是我得到的錯誤是:

System.NullReferenceException被未處理的HResult = -2147467261消息=對象引用不設置爲一個對象的一個​​實例。

是否有使用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

你可以使用LINQ到,你需要使用在VLOOKUP和上VLOOKUP表中的第二查詢表查詢,然後再結合加入這兩個查詢。爲每個查詢結果運行一個循環以輸出您的excel文件列。

+0

因爲我是這個編碼世界的新手。我需要時間來理解解決方案。感謝您的答覆,我將學習LINQ在vb.net – user3094480

+0

看看這篇文章http://stackoverflow.com/questions/1485958/read-excel-using-linq。我認爲您會對當前項目的簡單易用性感到驚訝。 –

相關問題