複制以下代碼到excel宏中執行
Sub 手動選擇檔案夾插入對象圖示()
Dim objWord As Object
Dim objDoc As Object
Dim strPath As String
Dim strFolder As String
Dim i As Integer
Dim arrFiles() As String
Dim j As Integer
Dim temp As String
Dim startRow As Integer
'手動選擇檔案夾路徑
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "請選擇要插入的 Word 文檔所在的檔案夾"
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub
strFolder = .SelectedItems(1)
End With
'擷取檔案夾内的所有Word文檔
strPath = Dir(strFolder & "\*.docx")
i = 0
Do While strPath <> ""
ReDim Preserve arrFiles(i)
arrFiles(i) = strPath
i = i + 1
strPath = Dir
Loop
'按類型排序
For i = 0 To UBound(arrFiles) - 1
For j = i + 1 To UBound(arrFiles)
If UCase(Right(arrFiles(i), 4)) > UCase(Right(arrFiles(j), 4)) Then
temp = arrFiles(i)
arrFiles(i) = arrFiles(j)
arrFiles(j) = temp
End If
Next j
Next i
'打開Word文檔
Set objWord = CreateObject("Word.Application")
'從光标所在單元格開始插入對象圖示
startRow = ActiveCell.Row
startRow = startRow + 1
For j = 0 To UBound(arrFiles)
Set objDoc = objWord.Documents.Open(strFolder & "\" & arrFiles(j))
ActiveSheet.OLEObjects.Add(Filename:=strFolder & "\" & arrFiles(j), Link:=False, DisplayAsIcon:=True, _
IconFileName:="C:\PROGRA~2\Microsoft Office\Office14\WINWORD.EXE", _
IconIndex:=0, IconLabel:=arrFiles(j)).Select
Cells(startRow, ActiveCell.Column).Select
startRow = startRow + 1 '插入下一行
objDoc.Close SaveChanges:=False
Next j
'關閉Word文檔
objWord.Quit
End Sub
這段 VBA 代碼用于在 Excel 中插入 Word 文檔的對象圖示。具體實作過程如下:
- 手動選擇檔案夾路徑:使用 Application.FileDialog 對象打開檔案夾選擇對話框,讓使用者手動選擇要插入的 Word 文檔所在的檔案夾。
- 擷取檔案夾内的所有 Word 文檔:使用 Dir 函數擷取指定檔案夾内的所有 Word 文檔,并将它們的檔案名存儲在一個字元串數組中。
- 按類型排序:使用冒泡排序算法,按照檔案類型(即檔案擴充名)對字元串數組進行排序,以便按照順序插入 Word 文檔的對象圖示。
- 打開 Word 文檔:使用 CreateObject 函數建立 Word 應用程式對象,并使用 Documents.Open 方法打開每個 Word 文檔。
- 插入對象圖示:使用 ActiveSheet.OLEObjects.Add 方法在 Excel 中插入 Word 文檔的對象圖示,并使用 Cells 屬性指定插入對象圖示的單元格。
- 關閉 Word 文檔:使用 Close 方法關閉每個 Word 文檔,并使用 Quit 方法關閉 Word 應用程式對象。
在這段代碼中,還使用了一些 VBA 對象和方法,例如 Application.FileDialog 對象、Dir 函數、ReDim Preserve 語句、冒泡排序算法、CreateObject 函數、Documents.Open 方法、ActiveSheet.OLEObjects.Add 方法、Cells 屬性、Close 方法和 Quit 方法等。