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

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

但是,有时候用户会进入这些地址,并在地址之间不小心添加一个空格或空行,导致整个代码崩溃。

如何在使用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) 

你将添加两行,将忽略这样的空行和空格:

 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) 

build议你添加更多的代码

  • testing文件是否真的存在
  • testing该文件是否为excel打开的有效types

 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