Function GetAllDocFiles(folderPath As String) As String()
' 搜尋指定目錄及其子目錄下所有 .doc 檔案的路徑
Dim fileNames() As String
ReDim fileNames(0)
Dim fileName As String
fileName = Dir(folderPath & "\*.doc", vbNormal)
While fileName <> ""
If fileName <> "." And fileName <> ".." Then
' 將找到的 .doc 檔案加入陣列中
fileNames(UBound(fileNames)) = folderPath & "\" & fileName
ReDim Preserve fileNames(UBound(fileNames) + 1)
End If
fileName = Dir()
Wend
Dim subFolderPath As String
subFolderPath = Dir(folderPath & "\*", vbDirectory)
While subFolderPath <> ""
If subFolderPath <> "." And subFolderPath <> ".." Then
' 如果是目錄,就遞迴呼叫本身搜尋該目錄
If (GetAttr(folderPath & "\" & subFolderPath) And vbDirectory) = vbDirectory Then
Dim subFolderFiles() As String
subFolderFiles = GetAllDocFiles(folderPath & "\" & subFolderPath)
If UBound(subFolderFiles) > -1 Then
' 將子目錄中找到的 .doc 檔案加入陣列中
Dim i As Integer
For i = 0 To UBound(subFolderFiles)
fileNames(UBound(fileNames)) = subFolderFiles(i)
ReDim Preserve fileNames(UBound(fileNames) + 1)
Next i
End If
End If
End If
subFolderPath = Dir()
Wend
If UBound(fileNames) > 0 Then
ReDim Preserve fileNames(UBound(fileNames) - 1)
Else
ReDim fileNames(-1)
End If
GetAllDocFiles = fileNames
End Function
Sub ConvertDocToDocx()
' 將所有 .doc 檔案轉換為 .docx 檔案
Dim fileNames() As String
fileNames = GetAllDocFiles("C:\My Documents") ' 指定搜尋目錄
Dim fileName As String
For Each fileName In fileNames
Dim doc As Document
Set doc = Documents.Open(fileName)
doc.SaveAs2 FileName:=Replace(fileName, ".doc", ".docx"), FileFormat:=wdFormatXMLDocument
doc.Close
Next fileName
End Sub