2016-11-24 4 views
0

私は、基準1と基準2が合格した2つのTextBoxコントロールを持っています。この関数は、ファイルパス(destination1)で提供されるExcelファイルを開き、Sheet2では、vlookupはcol A、col Bを取り、col C値をtextbox3に戻す必要があります。2基準を行う方法データをExcelで照会する

Iを取得エラーがしかし:

System.NullReferenceExceptionは、未処理のHRESULT = -2147467261メッセージ=オブジェクト参照オブジェクトのインスタンスに設定されていませんでした。

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

あなたはその後、2つのクエリを結合する組み合わせ、あなたがVLOOKUPとVLOOKUPテーブル上の第二のクエリを使用している必要があるテーブルの上に照会するLINQを使用することができます。クエリ結果ごとにループを実行して、Excelファイルの列を出力します。

+0

私はこのコーディングの世界で初めてです。解決策を理解するには時間がかかります。返信いただきありがとうございます。私はvb.netでLINQを学ぶ – user3094480

+0

この投稿をチェックしてくださいhttp://stackoverflow.com/questions/1485958/read-excel-using-linq私はあなたが現在のプロジェクトにシンプルさと実装が簡単であることに驚かれると思います。 –

関連する問題