我需要编写一个VBA脚本,其中需要转到一个文件夹并打开具有特定扩展名(txt)的文件,然后保存而不进行任何更改,然后关闭该文件。
应在文件夹中循环并打开,保存,关闭所有带有txt扩展名的文件。
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "U:\test"
Set objFolder = objFSO.GetFolder(objStartFolder)
Wscript.Echo objFolder.Path
Set colFiles = objFolder.Files
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) ="txt" Then
colFiles.Activate
colFiles.save
colFiles.closedoc
End If
Next
请帮助
答案 0 :(得分:0)
如果我理解您的问题,则需要此代码:
Dim MyFolder As String
Dim MyFile As String
MyFolder = "U:\test" //path
MyFile = Dir(MyFolder & "\*.txt") //get all file with extension .txt
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile //open file *.txt
Workbooks(MyFile).Close SaveChanges:=True //close file and save
MyFile = Dir //next file *.txt
Loop
我尝试了此代码,并且工作正常。
希望这对您有所帮助。
编辑帖子: 试试这个,仅复制并粘贴到您的宏模块中
Sub controlFile()
Dim MyFolder As String
Dim MyFile As String
MyFolder = "U:\test" 'path
MyFile = Dir(MyFolder & "\*.txt") 'get all file with extension .txt
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile 'open file *.txt
Workbooks(MyFile).Close SaveChanges:=True 'close file and save
MyFile = Dir 'next file *.txt
Loop
End Sub
让我保持更新状态。(我在owindows 10上使用过Office 2013和2007,并且宏工作正常)。我没有收到任何错误。 当执行宏时,使用f8按钮一次执行一行代码