从文本文件中读取行但跳过前两行

时间:2009-06-02 10:13:08

标签: excel vba excel-vba ms-word text-files

我在Microsoft Office Word 2003中有这个宏代码,它读取文本文件的行。每行代表一个字符串值,我需要稍后在代码中使用。

但是,文本文件的前两行包含一些我不需要的东西。 如何修改代码以便跳过前两行? Word中的VBA编辑器中的“Intellisense”很糟糕......

无论如何,代码看起来像这样

Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String

sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
    MsgBox ("Cannot find fields.ini")
End If

iFileNum = FreeFile()
Open sFileName For Input As iFileNum
Do While Not EOF(iFileNum)
    Line Input #iFileNum, Fields

    MsgBox (Fields)

这段代码目前给了我所有的内容,我不想要前两行。

5 个答案:

答案 0 :(得分:30)

整个Open <file path> For Input As <some number>事情是所以 90年代。它也很慢而且很容易出错。

在您的VBA编辑器中,从“工具”菜单中选择“引用”,然后查找“Microsoft Scripting Runtime”(scrrun.dll),它应该可以在任何XP或Vista计算机上使用。它就在那里,选择它。现在您可以访问(至少对我来说)更强大的解决方案:

With New Scripting.FileSystemObject
    With .OpenTextFile(sFilename, ForReading)

        If Not .AtEndOfStream Then .SkipLine
        If Not .AtEndOfStream Then .SkipLine

        Do Until .AtEndOfStream
            DoSomethingImportantTo .ReadLine
        Loop

    End With
End With

答案 1 :(得分:6)

您可以使用随机访问。

Open "C:\docs\TESTFILE.txt" For Random As #1 

    Position = 3    ' Define record number.
    Get #1, Position, ARecord    ' Read record.

Close #1

答案 2 :(得分:3)

Open sFileName For Input As iFileNum

Dim LineNum As Long
LineNum = 0

Do While Not EOF(iFileNum)
  LineNum = LineNum + 1
  Line Input #iFileNum, Fields
  If LineNum > 2 Then
    DoStuffWith(Fields)
  End If
Loop

答案 3 :(得分:2)

可能我过于简单了?

只需添加以下代码:

Open sFileName For Input as iFileNum
Line Input #iFileNum, dummy1
Line Input #iFileNum, dummy2
........

孙大信

答案 4 :(得分:1)

Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String
Dim TempStr as String

sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
    MsgBox ("Cannot find fields.ini")
End If

iFileNum = FreeFile()
Open sFileName For Input As iFileNum

''//This part skips the first two lines
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr

Do While Not EOF(iFileNum)
    Line Input #iFileNum, Fields

    MsgBox (Fields)
Loop