首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Excel文件中查找字符串并获取行索引

在Excel文件中查找字符串并获取行索引
EN

Stack Overflow用户
提问于 2019-06-06 02:52:10
回答 1查看 95关注 0票数 2

我正在尝试通过Word访问Excel文件并搜索字符串。

我尝试获取整个行(例如:我在单元格A7中查找字符串"Hello world“,然后尝试获取第7行中的所有日期),然后将该信息放入我的Word文件中的一个精确位置。

以下是Excel文件的示例:

No       site           trig           type 
1        steve          stv            7
2        Nancy          nco            3

等等。

Public Function test(ByVal strTitle As String, ByVal strTrigram As String) As String
    Dim xlApp As Object
    Dim xlBook As Object
    Dim strName As String
    Dim col As Column

    On Error Resume Next
    Set xlApp = GetObject(, "Excel.Application")
    If Err Then
        Set xlApp = CreateObject("Excel.Application")
    End If
    On Error GoTo 0
    Set xlBook = xlApp.Workbooks.Open(ActiveDocument.Path & "/FichierTrigrammes.xlsx")
    xlApp.Visible = False  'does not open the file, read only => faster to get the info

    With xlBook.Sheets(1).Cells
        Set rfind = .Find(What:=strTitle) ' on cherche si il y a ue colonne avec le nom
        If rfind Is Nothing Then
            MsgBox "Pas de colonne avec ce titre"
            Exit Function
        End If
        MsgBox rfind.Column
        'Debug.Print "L'index de la colonnne" & titleCol &; " est "; rfind.Column
    End With

    Dim ra As Range

    Set ra = Cells.Find(What:="SLD", LookIn:=xlFormulas, LookAt _
      :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
      False, SearchFormat:=False) 'there is a pb with find

    If ra Is Nothing Then
        MsgBox "Not found"
        Else
        MsgBox ra.Address
    End If         

    strName = "okay"
    'strName = xlBook.Sheets(1).Cells.Find(what:=strTrig)
    xlBook.Close False ' no save
    Set src = Nothing
    Set xlApp = Nothing
    Set xlBook = Nothing
    test = strName

End Function

我正在尝试搜索Excel文件中的标题是否是我需要的,然后定位字符串(应该在这里),并获取行索引以获取整行,但弹出一个错误,指出find方法有问题。

EN

回答 1

Stack Overflow用户

发布于 2019-06-06 02:59:05

Set ra = Cells.Find(What:="SLD", LookIn:=xlFormulas, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False) 'there is a pb with find

Cells是Excel应用程序对象的一部分,而不是Word vba环境的一部分,因此您需要像上面那样对其进行限定

Dim ra As Object 'not Range

Set ra = xlBook.Sheets(1).Cells.Find(What:="SLD", LookIn:=xlFormulas, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56466404

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档