2017-03-01 114 views
0

我每月必須彙總每日文件。問題是我需要將這些文件放在「TXT」中,但它們會以「WRI」的形式發送給我。通過文件夾更改文件擴展名循環VBA

如果使用以下內容進行硬編碼,我可以一次執行一個文件。

Name "C:\Users\John\Desktop\Folder1\SQLEXEC.WRI" As "C:\Users\John\Desktop\Folder1\SQLEXEC.TXT" 

但是,我想能夠遍歷該文件夾。但我不知道如何更改代碼以允許它循環。

Sub ConvertToTXT() 

Application.DisplayAlerts = False 
Application.ScreenUpdating = False 

Dim strPath As String 
Dim strFile As String 

strPath = "C:\Users\John\Desktop\Folder1\" strFile = Dir(strPath & "*.wri") 

Do While strFile <> "" 

Name "C:\Users\John\Desktop\Folder1\SQLEXEC.WRI" As "C:\Users\John\Desktop\Folder1\SQLEXEC.TXT" 

Loop 

End Sub 
+0

看起來像你需要看看如何'Dir'工作。請參閱Documentation.SO上的[VBA主題](http://stackoverflow.com/documentation/vba/topics)。你的循環體也應該使用'strFile'作爲舊名稱,並且你需要邏輯來刪除/替換新名稱中的擴展名。 –

回答

0
Sub ConvertToTXT() 

    Const strPath As String = "C:\Users\John\Desktop\Folder1" 
    Dim strFile As String 

    Application.DisplayAlerts = False 
    Application.ScreenUpdating = False 

    strFile = Dir(strPath & "\" & "*.wri") 

    Do While strFile <> "" 
     Name strPath & "\" & strFile As strPath & "\" & Replace(strFile, ".wri", ".txt") 
     strFile = Dir 
    Loop 

    Application.DisplayAlerts = True 
    Application.ScreenUpdating = True 

End Sub 
+0

感謝您的快速回復!我嘗試過使用它,但不幸的是,當它運行時,我不確定它在做什麼。它運行並且我沒有收到任何錯誤,但文件不會從WRI更改爲TXT。 – AlmostThere

+0

@Comintern使用F8運行以查看變量,尤其是查看是否使用文件夾中的名稱加載了strFile。我使用不同的擴展名在我的電腦上測試過,它確實有效。仔細檢查你的文件夾地址,以及你是否有任何文件是wri。執行該行時檢查strFile(黃色),將鼠標懸停在其上以顯示其值。它應該選擇wri文件的名稱 – Ibo

0

我個人使用Scripting.FileSystemObject本 - 這是容易得多誤差比手動構建文件路徑字符串。你需要添加一個引用到Microsoft腳本運行時:

Private Sub ConvertToTXT(filePath As String) 
    With New Scripting.FileSystemObject 
     Dim directory As Folder 
     Set directory = .GetFolder(filePath) 
     Dim target As File 
     For Each target In directory.Files 
      If LCase$(.GetExtensionName(target.Name)) = "wri" Then 
       Dim newName As String 
       newName = .BuildPath(filePath, .GetBaseName(target.Name)) & ".txt" 
       .MoveFile target.Path, newName 
      End If 
     Next 
    End With 
End Sub 

調用它通過傳遞它的目錄要在執行重命名:

ConvertToTXT "C:\Users\John\Desktop\Folder1" 

注意,是不介意有一個尾隨\或不 - 這也行得通:

ConvertToTXT "C:\Users\John\Desktop\Folder1\"