使用 vb.net 在 Excel 表中查找特定数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24230445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:41:52  来源:igfitidea点击:

Find specific data in excel sheet using vb.net

vb.netwinformsexcelwinforms-interop

提问by user3363495

I have been trying to find a specific data in Excel through a WinForm application and then try to fetch the next value in the same row using vb.net.

我一直在尝试通过 WinForm 应用程序在 Excel 中查找特定数据,然后尝试使用 vb.net 获取同一行中的下一个值。

Example:
ElementName Value
Age          24
Name    John Clan
Music   Rock

Suppose if I want to find Age. then I want to make the code return as 24 searching it from Excel file.

假设我想找到年龄。然后我想让代码返回为 24 从 Excel 文件中搜索它。

I tried pulling the whole Excel data into a Dataset but it wasn't helpful.

我尝试将整个 Excel 数据拉入数据集,但没有帮助。

Kindly guide me.

请指导我。

回答by user3363495

Imports Interop = Microsoft.Office.Interop.Excel

'Find In Excel
    Private Function FindValueInExcel(ByVal sTextToFind)
        Dim currentFind As Interop.Range = Nothing
        Dim firstFind As Interop.Range = Nothing
        Dim xlappFirstFile As Interop.Application = Nothing
        Dim sSearchedValue As String

        xlappFirstFile = CreateObject("Excel.Application")

        xlappFirstFile.Workbooks.Open("D:\Sample.xlsx")

        Dim rngSearchValue As Interop.Range = xlappFirstFile.Range("A1", "C5")

        currentFind = rngSearchValue.Find(sTextToFind, , _
            Interop.XlFindLookIn.xlValues, Interop.XlLookAt.xlPart, _
            Interop.XlSearchOrder.xlByRows, Interop.XlSearchDirection.xlNext, False)

        If Not currentFind Is Nothing Then
            sSearchedValue = DirectCast(DirectCast(currentFind.EntireRow, Microsoft.Office.Interop.Excel.Range).Value2, System.Object)(1, 3).ToString()
        Else
            sSearchedValue = ""
        End If

        Return sSearchedValue 

    End Function

Link which helped me - http://msdn.microsoft.com/en-us/library/e4x1k99a.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

帮助我的链接 - http://msdn.microsoft.com/en-us/library/e4x1k99a.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1