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