62

我正在尝试使用 VBA 解析文本文档并返回文本文件中给出的路径。例如,文本文件如下所示:

*Blah blah instructions
*Blah blah instructions on line 2
G:\\Folder\...\data.xls
D:\\AnotherFolder\...\moredata.xls

我希望 VBA 一次加载 1 行,如果它以 a 开头,*则移至下一行(类似于被注释的那一行)。对于具有文件路径的行,我想将该路径写入单元格,例如A2第一个路径、B2下一个路径等。

我希望回答的主要问题是:

  1. 使用 VBA 读取文本文件的最佳/简单方法是什么?
  2. 我怎样才能逐行做到这一点?
4

5 回答 5

79

对于文本文件的最基本读取,请使用open

例子:

Dim FileNum As Integer
Dim DataLine As String

FileNum = FreeFile()
Open "Filename" For Input As #FileNum

While Not EOF(FileNum)
    Line Input #FileNum, DataLine ' read in data 1 line at a time
    ' decide what to do with dataline, 
    ' depending on what processing you need to do for each case
Wend

#Author note - 请停止添加close #FileNum- 它已在评论中解决,不需要作为对此答案的改进

于 2012-07-17T18:48:56.800 回答
50

我发现带有 TxtStream 的 FileSystemObject 是读取文件的最简单方法

Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)

然后有了这个txtStream对象,你就拥有了智能感知的各种工具(与使用该FreeFile()方法不同),因此猜测工作更少。另外,您不必分配 FreeFile 并希望它实际上仍然是免费的,因为您分配了它。

您可以读取如下文件:

Do While Not txtStream.AtEndOfStream
    txtStream.ReadLine
Loop
txtStream.Close

注意:这需要参考 Microsoft Scripting Runtime。

于 2012-07-17T19:59:02.453 回答
39

为了完整性;处理加载到内存中的数据;

dim hf As integer: hf = freefile
dim lines() as string, i as long

open "c:\bla\bla.bla" for input as #hf
    lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf

for i = 0 to ubound(lines)
    debug.? "Line"; i; "="; lines(i)
next
于 2012-07-18T13:06:39.637 回答
2

您可以使用此代码在文本文件中逐行读取,还可以检查第一个字符是否为“*”,然后您可以保留它..

Public Sub Test()

    Dim ReadData as String

    Open "C:\satheesh\myfile\file.txt" For Input As #1

    Do Until EOF(1) 
       Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
    If Not Left(ReadData, 1) = "*" then
       '' you can write the variable ReadData into the database or file
    End If 

    Loop

    Close #1

End Sub
于 2012-12-26T17:09:02.070 回答
-2

下面是我从读取文本文件到 excel 文件的代码。

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub
于 2019-11-14T07:39:43.837 回答