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

时间:2019-06-05 18:52:09

标签: excel vba ms-word word-vba

我是这里的新手,也是VBA中的新手。 我想做的是通过单词访问Excel文件并搜索字符串。此后,我试图获取整行(例如:我在A7中寻找字符串“ Hello world”,然后尝试将row 7中的所有日期都放入我的word文件中),然后将该信息放入我的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处有pb。

如果有人可以帮助我,我将不胜感激(我喜欢在VBA中进行3天的编码,所以不要介意告诉您代码有什么问题)

也许它不够清晰,请在评论部分告诉我。

1 个答案:

答案 0 :(得分:2)

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)