阅读时忽略文本文件中的空行和空格

时间:2015-12-15 15:47:00

标签: excel vba text

我有一个文本文件,其中文件地址逐行列出。

但是,有时候,用户会进入那里并意外地在地址之间添加空格或空行,从而导致整个代码崩溃。

使用VBA读取文件时如何避免这种情况?

这是用于打开文本文件并逐行读取地址的当前块:

Set ActiveBook = Application.ActiveWorkbook

PathFile = ActiveWorkbook.Path & "\FilePaths.txt"
Open PathFile For Input As #1

Do Until EOF(1)
    Line Input #1, SourceFile            
    Set Source = Workbooks.Open(SourceFile)

2 个答案:

答案 0 :(得分:2)

您将添加两行,将忽略空行和空格,如下所示:

Line Input #1, SourceFile
SourceFile = Trim(SourceFile)    '~~> This will trim all the spaces
If Not SourceFile = "" Then      '~~> This will check if lines is empty
    Set Source = Workbooks.Open(SourceFile)

答案 1 :(得分:1)

建议您向

添加更多代码
  • 测试文件是否确实存在
  • 测试文件是否为excel打开的有效类型

Dim SourceFile As String
Dim PathFile As String
Set ActiveBook = Application.ActiveWorkbook

PathFile = ActiveWorkbook.Path & "\FilePaths.txt"
Open PathFile For Input As #1

Do Until EOF(1)
    Line Input #1, SourceFile
    SourceFile = Trim$(SourceFile)
    If Len(Dir(ActiveWorkbook.Path & "\" & SourceFile)) > 0 Then
         Select Case Right$(SourceFile, Len(SourceFile) - InStrRev(SourceFile, "."))
         Case "xls", "xls*"
         Set Source = Workbooks.Open(ActiveWorkbook.Path & "\" & SourceFile)
         Case Else
         Debug.Print "source not valid"
         End Select
    End If
Loop