【发布时间】:2019-05-20 14:42:49
【问题描述】:
我正在尝试在 Excel 和 Word 中创建从 Excel 中的行创建 Word 文档的脚本。我基于“dotm”模板中的 Word 文档。使用“dotx”文件格式一切正常(并且仍然正常),但是一旦我使用启用宏,我就会收到 5981 运行时错误应用程序定义或对象定义错误。
我已经在网上进行了研究,并尝试了所有修复,包括在 Word 中启用宏、受信任的位置和受信任的文档。在尝试访问之前,我已经尝试过 DoEvent。我需要访问“dotm”文件,因为 Word 中有宏需要在打开时运行以格式化文档。
有人可以请帮助我吗?我在 VBA 方面没有经验,我的话题已经结束了。
Set objword = GetObject(, "Word.Application")
If objword Is Nothing Then
Set objword = CreateObject("Word.Application")
End If
On Error GoTo 0
Set objDoc = objword.Documents.Add("C:\Users\OMITTED FOR PRIVACY\Test Report.dotm")
结果... 预期:创建和格式化的 Word 文档 实际:运行时错误“5981”:应用程序定义或对象定义错误
更新
Test Report.dotm 文件中的代码:
Sub conditionalFormat()
Dim oCell As Word.Cell
Dim oColumn As Word.Column
'First set of tables
For intI = 2 To 5
Set oColumn = ActiveDocument.Tables(intI).Range.Columns(3)
For Each oCell In oColumn.Cells
If IsNumeric(Left(oCell.Range.Text, Len(oCell.Range.Text) - 2)) Then
If Val(oCell.Range.Text) < 55 Then
oCell.Shading.ForegroundPatternColor = wdColorRed
oCell.Range.Font.TextColor = wdColorWhite
oCell.Range.Font.Bold = True
oCell.Range.InsertAfter Text:="%"
ElseIf Val(oCell.Range.Text) > 55 And Val(oCell.Range.Text) < 75 Then
oCell.Shading.ForegroundPatternColor = wdColorLightOrange
oCell.Range.Font.TextColor = wdColorWhite
oCell.Range.Font.Bold = True
oCell.Range.InsertAfter Text:="%"
ElseIf Val(oCell.Range.Text) > 75 Then
oCell.Shading.ForegroundPatternColor = wdColorSeaGreen
oCell.Range.Font.TextColor = wdColorWhite
oCell.Range.Font.Bold = True
oCell.Range.InsertAfter Text:="%"
End If
End If
Next
Next intI
'Analysis set of tables
For intI = 8 To 28 Step 3
Set oColumn = ActiveDocument.Tables(intI).Range.Columns(4)
For Each oCell In oColumn.Cells
If IsNumeric(Left(oCell.Range.Text, Len(oCell.Range.Text) - 2)) Then
If Val(oCell.Range.Text) < 33.3 Then
oCell.Shading.ForegroundPatternColor = wdColorRed
oCell.Range.Font.TextColor = wdColorWhite
oCell.Range.Font.Bold = True
oCell.Range.InsertAfter Text:="%"
ElseIf Val(oCell.Range.Text) > 33.3 And Val(oCell.Range.Text) < 66.6 Then
oCell.Shading.ForegroundPatternColor = wdColorLightOrange
oCell.Range.Font.TextColor = wdColorWhite
oCell.Range.Font.Bold = True
oCell.Range.InsertAfter Text:="%"
ElseIf Val(oCell.Range.Text) > 66.6 Then
oCell.Shading.ForegroundPatternColor = wdColorSeaGreen
oCell.Range.Font.TextColor = wdColorWhite
oCell.Range.Font.Bold = True
oCell.Range.InsertAfter Text:="%"
End If
End If
Next
Next intI
End Sub
【问题讨论】:
-
实际上这看起来像模板宏中有错误或marco文件不受信任。如果您手动打开模板文件
.dotm(双击文件)会发生什么?它是在受保护的视图中打开还是显示宏已禁用?那么宏会运行吗?请检查。 -
我已删除并重新保存了
.dotm文件,但该文件无法解决任何问题。当我打开文件时,它很好,不会在受保护的视图中打开,也不会禁用宏。我专门将该文件夹添加到 受信任的位置 列表中。我还启用了所有宏运行,但似乎没有任何工作:'( -
要测试这是与代码相关的问题还是一般宏问题,请测试以下内容:创建一个全新的文件
Hello World.dotm并在Document_Open()事件中添加以下代码:MsgBox "I run fine"。然后用你的代码测试这个文件。如果您收到相同的错误,这是一个一般性的宏问题(如信任),如果它显示消息框,那么您的报告文件的代码中存在问题。 -
我已经测试过了,它似乎工作正常,所以它一定是报告文件中的代码有问题。我已经用我的报告文件中的代码更新了我的原始代码。你能告诉我哪里出错了吗?
-
非常感谢
PEH您的解决方案解决了我的问题。它现在应该这样做。如果您想提交作为答案,我会接受它作为答案:)
标签: excel vba ms-word runtime-error