Excel vba是否读取文本文件中的所有文本?
我正在尝试使用vba读取文本文件中的所有文本,并将其显示在excel消息框中。我的问题是,虽然这是有效的工作,它显示在一个单独的消息框中的每一行文字,而不是我希望它都在一个 有人能告诉我哪里出了问题吗。谢谢Excel vba是否读取文本文件中的所有文本?,excel,vba,text-files,Excel,Vba,Text Files,我正在尝试使用vba读取文本文件中的所有文本,并将其显示在excel消息框中。我的问题是,虽然这是有效的工作,它显示在一个单独的消息框中的每一行文字,而不是我希望它都在一个 有人能告诉我哪里出了问题吗。谢谢 If Range("L" & ActiveCell.Row).Value = "Performance" Then Dim FilePath As String Dim strLine As String FilePath = "\\UKSH000-FILE06\Purchasing
If Range("L" & ActiveCell.Row).Value = "Performance" Then
Dim FilePath As String
Dim strLine As String
FilePath = "\\UKSH000-FILE06\Purchasing\New_Supplier_Set_Ups_&_Audits\ATTACHMENTS\" & Range("C" & ActiveCell.Row).Value & "\performance.txt"
Open FilePath For Input As #1
While EOF(1) = False
'read the next line of data in the text file
Line Input #1, strLine
'print the data in the current row
MsgBox strLine
'increment the row counter
i = i + 1
Wend
Close #1
End If
您需要将文本累积到单独的字符串中:
标注字符串作为字符串写入循环之前
MsgBox
替换为strAll=strAll&strLine
MsgBox strAll
&
用于在VBA中连接字符串。可以使用空格分隔各行:
strAll=strAll&&strLine
甚至多行
strAll=strAll&vbCrLf&strLine
其中
vbCrLf
是一个VBA常量,表示“回车后换行”。您将在字符串的开头引入一个额外的空格/换行符,但我将把它留给您来修复 在循环中,必须将所有行串联为字符串变量,并在末尾输出结果。基本上是这样的:
Dim Total As String
' ...
While EOF(1) = False
'read the next line of data in the text file
Line Input #1, strLine
Total = Total & vbNewLine & strLine
'increment the row counter
i = i + 1
Wend
MsgBox Total
注意:当此解决方案工作时,对于大型文件,它可能不是非常有效,因为看起来像是代码中的串联,实际上意味着将现有内容复制到新的内存位置,然后插入新行的字符串。每一行都是这样。因此,对于1000行,递增的总字符串被复制大约999次