VB6 - 无法完整读取Excel文件

时间:2013-01-31 11:59:18

标签: excel file vb6 xls

无论我尝试什么方法(目前我正在使用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:\Users\Admin\Desktop\ara\DOSYA.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中打开它可以正常工作。

1 个答案:

答案 0 :(得分:2)

你想要实现的目标(来自所讨论的评论)不是问题 - 下面是我快速生成的一段代码,主要使用来自宏录制器的部分:

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对象。