【发布时间】:2023-02-20 19:34:35
【问题描述】:
在一些用户的帮助下,我编译了一个宏,它从 excel 工作簿中获取某些值并将它们复制到 word 模板中。宏有时工作正常,但其他人,我收到错误 - “运行时错误 -2146950355 (80080005):服务器执行失败”。我不确定为什么我有时会收到此错误,而其他错误则不会。附件是我的代码和错误和调试的屏幕截图。
Const FilesPath As String = "filespath"
Const FilesPathh As String = "filespathh"
Const FilesPathhh As String = "filespathhh"
Const TemplateFile As String = "tempa.docx"
Sub Letters()
Dim wd As Word.Application, doc As Word.Document
Dim NomCell As Range, ws As Worksheet
Dim Result As Integer
Set ws = ActiveSheet
Set wd = New Word.Application
wd.Visible = True
Columns("H:H").Select
Application.CutCopyMode = False
Selection.Copy
Columns("I:I").Select
Selection.Insert Shift:=xlToRight
Application.CutCopyMode = False
Columns("I:I").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Columns("J:J").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Columns("H:H").Select
Selection.TextToColumns Destination:=Range("H1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=True, Other:=False, FieldInfo:= _
Array(Array(1, 1), Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True
Range("H1").Select
ActiveCell.FormulaR1C1 = "Last Name"
Range("I1").Select
ActiveCell.FormulaR1C1 = "First Name"
Range("J1").Select
ActiveCell.FormulaR1C1 = "Other"
For Each NomCell In ws.Range("A2", ws.Cells(Rows.Count, 1).End(xlUp)).Cells
'open as read-only
Set doc = wd.Documents.Open(FilesPath & TemplateFile, ReadOnly:=True)
With NomCell.EntireRow
doc.Bookmarks("date").Range.Text = Date
doc.Bookmarks("name").Range.Text = .Columns("I").Value
doc.Bookmarks("course").Range.Text = .Columns("A").Value
.Columns("A").Select
Selection.Replace What:="&", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
Selection.Replace What:=":", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
Selection.Replace What:="/", Replacement:=" ", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
doc.SaveAs2 FilesPathh & .Columns("K").Value & " " & .Columns("A").Value & ".pdf", _
wdExportFormatPDF
doc.Close False
End With
Next NomCell
wd.Quit
ActiveSheet.Cells.ClearContents
Result = MsgBox("The letters have been created. Would you like to view them?", vbYesNo)
If Result = vbYes Then
Call Shell("explorer.exe " & FilesPathhh, vbNormalFocus)
End If
End Sub
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
使用另一种方法加载 Word:link 和 DIM 一些未定义的变量:Templatefile,(为什么这三个?:FilesPath,FilesPathh,FilesPathhh)
-
并用一些文本加载这些提到的变量,因为它们在示例代码中作为空字符串传递
-
您何时何地自动化 Excel 和 Word?
标签: excel vba ms-word office-automation