简体   繁体   中英

VBA how to open/save/close file with extension from one folder

I need to write a VBA script in which i need to go to one folder and open file with specific extension (txt) and save without making any changes and then close the file.

It should loop in the folder and open,save ,close all the file with txt extension.

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

Please help

if i understood your question you need of this code:

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

I tried this code and works fine.

Hope this help you.

EDIT post: try this one, copy and paste only, in your macro module

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

Keep me updated..(i used office 2013 and 2007 on owindows 10 and macro works fine).I don't obtain anything error. When execute macro use f8 button to execute one code row at time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM