vba读取文本文件中的所有文本?

我正在尝试使用vba读取文本文件中的所有文本,并将其显示在excel消息框中。 我遇到的问题是,虽然这是有效的工作,它显示在一个单独的消息框中的每一行文本,而不是我希望它在一个?

有人可以告诉我哪里错了。 谢谢

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 

在你的循环中,你必须连接所有的行variables,并在结尾输出结果。 基本上是这样的:

 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 

注意:虽然这个解决scheme正在工作,但是对于大文件来说,由于看起来像代码中的连接,事实上意味着将现有内容复制到新的内存位置,然后插入新行的string。 这是为每一行完成的。 因此,对于1000行,总共大约999次的string被复制出来。

您需要在单独的string中累积文本:

  1. 在循环之前写入Dim strAll As String
  2. strAll = strAll & strLinereplace循环中的MsgBox
  3. 循环之后,使用MsgBox strAll

&用于在VBA中连接string。 你可以用一个空格分隔各行:

strAll = strAll & " " & strLine

甚至多线

strAll = strAll & vbCrLf & strLine

其中vbCrLf是一个VBA常量,意思是“回车后跟换行”。 你会在string的开始处引入一个额外的空格/换行符,但是我会留给你修复!