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

标签 excel vba ms-word

我正在尝试通过 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处。

最佳答案

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)

关于excel - 在 Excel 文件中查找字符串并获取行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56466404/

相关文章:

vba - Excel UDF查找具有给定值的范围内的第一个和最后一个单元格-运行缓慢

excel - 在 Excel 和 VBA 中,如何将单元格的值设置为公式结果而不是公式

excel - 编辑工作表并打开弹出消息窗口

html - 样式标签排除具有特定样式的标签

vb.net - 在形状集合中混淆索引越界

vba - 宏选择和范围,改变格式,偏移然后循环

java.lang.ClassNotFoundException : jxl. read.biff.BiffException

vba - 保存工作簿时删除非法字符 Excel VBA

xml - VBA - 显示每个节点及其来自 XML 的值

excel - 从当前打开的从 Sharepoint 下载的 Word 文档 .docm 中获取字节数组,而不保存到本地驱动器