下面的代码段是从一个较大的项目中修改而来的,在该项目中,我从文本文件收集了数据并将其输出到Excel表(VBA listobject)。该代码循环遍历指定文件夹中的所有文本文件,以查找符合特定条件的文件。有效文件的标头在第一行包含标签## DATA FILE ##
,在随后的几行包含一些元数据。我正在使用Microsoft脚本运行时的FileSystemObject
打开这些文件,并逐行循环。对于此示例,我假设我在文件夹C:\MyFolder
中有一个文本文件,该文件的第一行带有有效标签,例如,内容如下:
## DATA FILE ##
Version: 49
123 456 789 Some information
111 444 000 Further items
使用此设置,下面的代码应平稳执行,并将“测试通过”输出到立即窗口。如果修改了标语行,则代码应改为显示一个消息框,要求用户提供进一步的说明。
现在,如果文本文件的第一行不包含必需的标记,我想添加一个选项,以便在运行时在记事本中手动打开和编辑该文件,然后继续执行。我已经准备好“是-否取消”消息框,该消息框可用于决定要做什么,但是如何在运行时打开文件进行手动编辑?
Option Explicit
Sub LoopThroughFiles()
' Loops through text files looking for files matching some conditions.
' Files that match are processed further.
' For files that don't match, the user can choose to inspect and
' modify the source file.
' Requires that a reference is set to Tools -> References
' -> Microsoft Scripting Runtime
Dim FSO As FileSystemObject
Dim TSO As TextStream
Dim oFolder, oFile As Object
Dim sFileName, sLine, sMsg As String
Dim lMsg As Long
Const sPath As String = "C:\MyFolder\"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = FSO.GetFolder(sPath)
' Loop through files:
For Each oFile In oFolder.Files
sFileName = oFile.Name
' Treat only text files:
If Right(sFileName, 4) = ".txt" Then
Set TSO = FSO.OpenTextFile(sPath & sFileName, ForReading)
' Check that conditions are met:
sLine = TSO.ReadLine
If Not sLine = "## DATA FILE ##" Then
sMsg = "The following file does not seem to " & _
"contain valid input data:" & vbNewLine & vbNewLine
sMsg = sMsg & sFileName & vbNewLine & vbNewLine
sMsg = sMsg & "Would you like to manually inspect " & _
"the file?" & vbNewLine & _
"(Click No to continue running the script " & _
"; Cancel to exit.)"
lMsg = MsgBox(sMsg, vbYesNoCancel)
Debug.Print lMsg
Stop
'
' OPTION HERE TO MANUALLY OPEN AND EDIT THE TEXT FILE IN NOTEPAD
'
Else
Debug.Print "Test passed"
' Other code here to further process valid data.
End If
TSO.Close
End If
Next oFile
End Sub
答案 0 :(得分:1)
Dim yourTextFile As String: yourTextFile = "C:\Sample.txt"
Call Shell("notepad.exe """ & yourTextFile & """", vbNormalFocus)
使用Shell
打开选定的文本文件。