如何在Excel工作表中搜索文本框值并将数据返回到其他文本框

时间:2016-11-23 09:58:20

标签: excel vb.net

我是VB.Net的新手,我学会了如何将数据从Excel提取到DataGridView。现在有人可以帮助我学习如何将Excel数据导入文本框吗?

我有一个包含6个文本框和一个搜索按钮的表单。当我在textbox1中输入值并单击搜索按钮时,我想搜索由OpenFileDialog选择并保存在destination1字符串中的Excel文件

destination1 = destipath & Filename.Text & "_" & dtedate.ToShortDateString & ".xlsx" '& Format(TimeOfDay, "h.mm.ss tt")

Excel sheet1有ID,姓名,父亲,母亲,地址和电话。 VB.Net表单有6个文本框。例如,当我在textbox1中输入ID为30时,代码必须在A列中搜索ID 30.如果找到,则文本框2-6必须显示姓名,父亲,母亲,地址,电话。

工作表行是动态的,但列是固定的。我已经编写了在Excel VBA中执行此操作的代码,但是我在编写代码时遇到了麻烦,无法在VB.Net中完成吗?

我在VB.Net中尝试过此操作但未在Excel中识别出LookInLookAt

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
    Dim xlappFile As Excel.Application = Nothing
    Dim xlFile_WB As Excel.Workbook = Nothing
    Dim xlFile_WS As Excel.Worksheet = Nothing
    Dim xlFirstfile_WS1 As Excel.Worksheet = Nothing
    Dim FoundRange As Excel.Range
    Dim searchID As String
    searchID = Textbox1.Text

    xlFile_WB = xlappFile.Workbooks(destination1) ' destination1 is selected by 'user
    MessageBox.Show(destination1)
    xlFile_WS = xlappFile.Worksheets(1)
    FoundRange = xlFile_WS.Cells.Find(What:=searchID, LookIn:=Excel.XlFindLookIn.xlFormulas, LookAt:=Excel.XlLookAt.xlWhole)

    If FoundRange Is Nothing Then
        textbox2.Text = "not found"
        textbox3.Text = "not found"
        textbox4.Text = "not found"
        textbox5.Text = "not found"
        textbox6.Text = "not found"
    Else
        textbox2.Text = FoundRange.Offset(0, 2).Value
        textbox3.Text = FoundRange.Offset(0, 3).Value
        textbox4.Text = FoundRange.Offset(0, 4).Value
        textbox5.Text = FoundRange.Offset(0, 5).Value
        textbox6.Text = FoundRange.Offset(0, 6).Value
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

与Excel / VBA不同,在VB.net中,您需要按照命名空间来限定Excel常量,如下所示:

FoundRange = xlFile_WS.Cells.Find(What:=searchID, LookIn:=Excel.XlFindLookIn.xlFormulas, LookAt:=Excel.XlLookAt.xlWhole)