无论我尝试什么方法(目前我使用的是Scripting.FileSystemObject),我都无法正确读取此XLS文件。这是我的代码(我不想读取单元格,我想像读取文本文件一样读取文件)
Dim fso As New FileSystemObject
Dim f As File
Dim fsoStream As TextStream
Dim strLine As String
Set f = fso.GetFile("C:UsersAdminDesktoparaDOSYA.xls")
Set fsoStream = f.OpenAsTextStream(ForReading)
Do While Not fsoStream.AtEndOfStream
strLine = fsoStream.ReadLine
Text1.Text = Text1.Text & strLine
Loop
fsoStream.Close
Set fsoStream = Nothing
Set f = Nothing
Set fso = Nothing
我得到的只是文件的前 5-6 个字符,然后是更多的胡言乱语,仅此而已。如果我在 Excel 中打开它,它可以正常工作。
您想要实现的目标(来自有问题的注释)不是问题 - 下面是我动态生成的一段快速代码,主要使用宏录制器中的部分:
Sub SearchString()
Dim LookupString As String
Dim WS As Worksheet
Dim SearchResult As Range
Dim MatchString As Boolean
Dim SourceFolder As String
Dim FileName As String
SourceFolder = "D:DOCUMENTS" 'Trailing "" is required
LookupString = "abc"
FileName = Dir(SourceFolder & "*.xls?") 'Extension may be set using wildcards
Do While FileName <> ""
Application.DisplayAlerts = False
Application.Workbooks.Open (SourceFolder & FileName)
Application.DisplayAlerts = True
MatchString = False
For Each WS In Workbooks(FileName).Worksheets
Set SearchResult = WS.Cells.Find(What:=LookupString, LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, _
SearchFormat:=False)
If Not SearchResult Is Nothing Then MatchString = True
Next WS
If MatchString = True Then MsgBox "File: " & Chr(34) & FileName & Chr(34) & vbNewLine & "has " & Chr(34) & LookupString & Chr(34) & " string."
Application.DisplayAlerts = False
Workbooks(FileName).Close SaveChanges:=False
Application.DisplayAlerts = True
FileName = Dir
Loop
End Sub
这将遍历放入SourceFolder
的所有类型的 Excel 文件,并在找到定义的字符串时显示一条消息。书中的纸张数量及其隐藏/可见状态无关紧要。
共享示例文件:https://www.dropbox.com/s/ipmztbz6vu7y4qf/FilesLookupString.xlsm
我很确定您也可以将其调整为 DOC 文件:只需对可能不同的部分使用宏记录器,例如搜索。祝你好运!
如果您决定将 Excel 文件内容读取为"类似二进制"(但我建议不要这样做) - 查看ADODB.Stream
对象。