Найти строку в другом файле Excel и получить индекс строки - PullRequest
2 голосов
/ 05 июня 2019

Я новичок здесь и новичок в VBA.Я пытаюсь получить доступ к файлу Excel через слово и искать строку.После этого я пытаюсь получить всю строку (например: я ищу строку «Hello world» в A7, затем пытаюсь получить все даты, расположенные в row 7 в моем файле слов), а затем поместитьэта информация в моем файле слова в точном месте.

Вот пример файла 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.

Если кто-то может мне помочь, я был бы признателен (у меня 3 дня программирования на VBA, поэтому не стесняйтесь рассказывать, что не так с кодом)

Возможно, это не совсем понятно, пожалуйста, дайте мне знать в разделе комментариев.

1 Ответ

2 голосов
/ 05 июня 2019
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)
...