vba代码 将图片依次放入word表格中
时间: 2023-11-27 13:50:53 浏览: 413
以下是一个示例VBA代码,可以将指定文件夹中的所有图片依次插入到Word表格中:
```VBA
Sub InsertPicturesToTable()
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdTable As Word.Table
Dim wdRow As Word.Row
Dim wdCell As Word.Cell
Dim strFolder As String
Dim strPicPath As String
Dim intRow As Integer
Dim intCol As Integer
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
'设置文件夹路径
strFolder = "C:\Pictures\"
'初始化Word应用程序
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
'创建新文档
Set wdDoc = wdApp.Documents.Add
'创建新表格
Set wdTable = wdDoc.Tables.Add(wdDoc.Range, 3, 4)
'遍历文件夹中的所有图片
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFolder)
intRow = 1
intCol = 1
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile.Path) Like "jpg" Or objFSO.GetExtensionName(objFile.Path) Like "png" Then
'计算单元格位置
If intCol > wdTable.Columns.Count Then
intRow = intRow + 1
intCol = 1
Set wdRow = wdTable.Rows.Add
End If
Set wdCell = wdRow.Cells(intCol)
'插入图片
strPicPath = objFile.Path
wdDoc.InlineShapes.AddPicture FileName:=strPicPath, LinkToFile:=False, SaveWithDocument:=True, Range:=wdCell.Range
'调整图片大小
wdCell.Range.InlineShapes(1).Width = wdCell.Width - 10
wdCell.Range.InlineShapes(1).Height = wdCell.Height - 10
intCol = intCol + 1
End If
Next objFile
'释放对象
Set objFSO = Nothing
Set objFolder = Nothing
Set objFile = Nothing
Set wdCell = Nothing
Set wdRow = Nothing
Set wdTable = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
End Sub
```
该代码将创建一个3行4列的表格,并将指定文件夹中的所有jpg和png文件依次插入到表格中。你可以根据需要修改表格大小、行列数目以及文件夹路径和文件类型等参数。
阅读全文