excel - Dim As Word.Range For Excel to Word Script 的编译错误
问题描述
我正在关注这个 youtube 视频 ( https://www.youtube.com/watch?v=URF3ikW0Svc ),它允许我从 excel 写入 word 模板。但是,根据我的需要对其进行了编辑后,我在声明其中一个变量时很早就遇到了错误,我似乎无法弄清楚问题是什么。代码如下:
Option Explicit
Sub CreateWordDocumens()
Dim CustRow, CustCol, LastRow As Long
Dim DocLoc, TagName, TagValue, FileName As String
Dim WordDoc As Object, WordApp As Object
Dim WordContent As Word.Range
With Sheet1
'Open Word Template
DocLoc = Sheet1.Range("A2").Value
On Error Resume Next 'If Word is already running
Set WordApp = GetObject("Word.Application")
If Err.Number <> 0 Then
'Launch a new instance of Word
Err.Clear
'On Error GoTo Error_Handler
Set WordApp = GetObject("Word.Application")
WordApp.Visible = True 'Make the application visible to the user
End If
LastRow = .Range("B999").End(xlUp).Row 'Determine Last Row in Table
For CustRow = 3 To LastRow
Set WordDoc = WordApp.Documents.Open(FileName:=DocLoc, ReadOnly:=False) 'Open Template
For CustCol = 3 To 6 'Move Through the Columns
TagName = .Cells(2, CustCol).Value 'Tag Name
TagValue = .Cells(CustRow, CustCol).Value 'Tag Value
With WordDoc.Content.Find
.Text = TagName
.Replacement.Text = TagValue
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Next CustCol
If .Range("B2").Value = "PDF" Then
FileName = ThisWorkbook.Path & "\" & .Range("C3").Value & ".pdf" 'Create full file path and name
WordDoc.ExportAsFixedFormat OutputFileName:=FileName, ExportFormat:=wdExportFormatPDF
WordDoc.Close False
Else
FileName = ThisWorkbook.Path & "\" & .Range("C3").Value & ".docx" 'Create full file path and name
WordDoc.SaveAs FileName
End If
Next CustRow
WordApp Quit
End With
End Sub
在子例程的第 5 行(“Dim WordContent as Word.Range”)我得到编译错误:未定义用户定义的类型,尽管事实上这正是 youtube 教程中代码的设置方式。我确实引用了 Microsoft Office 16.0 对象库。
任何可能发生这种情况的想法将不胜感激。
解决方案
推荐阅读
- node.js - Nodejs - 如何设置 cron 作业在每 2 个星期日运行
- python - 如何同时标记直方图和函数?
- python - 不确定创建具有时间限制的计划生成器背后的逻辑
- c++ - 这个用于指针的 C++ OOP 概念是什么?
- r - 当我们使用多个 geom_bar 时如何添加多个图例?
- spring-boot - 为什么 SpringBoot 应用程序的堆内存使用量不断增加?
- javascript - 为什么 Vue.js 中从挂载钩子发送的 AJAX GET 请求总是忽略浏览器缓存?
- powershell - URL 健康检查 PowerShell 脚本在大多数站点上正确获取 HTTP 200,但在某些站点上不正确的“0”状态代码...API 超时问题?
- c++ - 这个警告“指向算术中使用的函数的指针”是什么意思?
- arrays - 为什么链表叫链表 为什么不链表?