計量標準自查表批量生成VBA思路
在Excel表中列出計量標準名稱、計量標準考核證書編號,打開word自查表,在表格中填入對應信息,保存到自查表文件夾中!使用For循環,批量生成!
Sub 導出到Word模板中()
Dim Sht_Workbook As Workbook
Dim Sht_Worksheet As Worksheet
Dim Str_standardName As String
Dim Str_DepartmentName As String
Dim Str_standardNumber As String
Dim WordApp As Object
Dim WordDocNew As Object
Dim filePath As String
Dim savePath As String
Dim i As Long
' 設置當前工作簿和工作表
Set Sht_Workbook = ThisWorkbook
Set Sht_Worksheet = Sht_Workbook.Sheets(1)
' 創建Word應用程序實例
On Error Resume Next
Set WordApp = GetObject(, "Word.Application")
If WordApp Is Nothing Then
Set WordApp = CreateObject("Word.Application")
End If
On Error GoTo 0
WordApp.Visible = True ' 可選:使Word可見
' Word模板文件路徑
filePath = ThisWorkbook.Path & "\" & "自查表模板.docx"
' 遍歷Excel中的行
For i = 2 To 150 ' 根據需要調整這個范圍
' 讀取單元格的值
Str_standardName = Sht_Worksheet.Cells(i, 3).Value
Str_standardNumber = Sht_Worksheet.Cells(i, 4).Value
Str_DepartmentName = Sht_Worksheet.Cells(i, 12).Value
' 基于模板創建一個新文檔
savePath = ThisWorkbook.Path & "\自查表\自查表-" & Str_DepartmentName & "-" & Str_standardName & ".docx"
Set WordDocNew = WordApp.Documents.Add(Template:=filePath) ' 使用模板添加新文檔
' 在新文檔的表格中填充數據
With WordDocNew.Tables(1)
.Cell(1, 4).Range.Text = Str_standardName ' 假設表格第一行是標題,我們從第二行開始填充數據(如果需要)
' .Cell(2, 2).Range.Text = Str_DepartmentName
.Cell(2, 4).Range.Text = Str_standardNumber
' 注意:這里可能需要根據你的實際表格結構調整行和列索引
' ... 其他必要的填充操作
End With
' 保存新文檔
WordDocNew.SaveAs (savePath)
savePath = ThisWorkbook.Path & "\自查表\自查表-" & Str_DepartmentName & "-" & Str_standardName & ".pdf"
WordDocNew.SaveAs savePath, FileFormat:=wdFormatPDF
' 關閉新文檔(可選)
WordDocNew.Close SaveChanges:=False ' 因為我們已經用SaveAs2保存了,所以這里不需要再次保存
' 清理(可選,但在這個循環中很重要以避免內存泄漏)
Set WordDocNew = Nothing
Next i
' 清理(可選,但在宏結束時是個好習慣)
Set WordApp = Nothing
End Sub
|
-
-
計量標準自查表生成 VBA.zip
2025-4-29 14:11 上傳
點擊文件名下載附件
下載積分: 金幣 -1
346.79 KB, 下載次數: 14, 下載積分: 金幣 -1
|