在Word里批量插入多个文件夹标题并把对应文件夹内图片放到标题下的vba代码
时间: 2024-10-11 12:16:22 浏览: 45
在Word文档中使用VBA(Visual Basic for Applications)编写宏来批量插入文件夹标题并添加其内的图片,可以按照以下步骤进行:
```vba
Sub InsertFolderTitlesAndImages()
Dim objShell As Object ' 创建shell对象处理文件操作
Dim objFldr As Object ' 文件夹对象
Dim strFolderPath As String
Dim objFiles() As Variant ' 存放文件路径数组
Dim i As Long
' 设置需要操作的文件夹路径
strFolderPath = "C:\Your\Folder\Path" ' 请替换为你实际的文件夹路径
' 获取文件夹及其内容
Set objShell = CreateObject("WScript.Shell")
Set objFldr = objShell.CreateExplorer(strFolderPath)
objFldr.Visible = False ' 隐藏文件浏览器窗口
objFiles = objFldr.Files ' 获取文件夹内的所有文件路径
' 清空并将文件夹标题和图片路径添加到数组
For Each file In objFiles
If Right(file.Path, 4) = ".jpg" Or Right(file.Path, 4) = ".png" Then
ReDim Preserve objFiles(i) ' 如果是图片则添加到数组
objFiles(i) = "<img src='" & file.Path & "' /> " & Mid(file.Name, InStrRev(file.Name, "\"), Len(file.Name))
i = i + 1
End If
Next file
' 插入标题并放置图片
With ActiveDocument.Range
.InsertAfter "<h2>文件夹:" & Replace(objFldr.Name, "\", "</span><br /><span>") '</h2> 标签后添加文件夹名
For j = LBound(objFiles) To UBound(objFiles)
.InsertAfter objFiles(j) ' 每次插入一行图片和描述
Next j
End With
' 关闭文件浏览器
objFldr.Close
Set objShell = Nothing
Set objFldr = Nothing
End Sub
```
阅读全文