首页 > 解决方案 > 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 对象库。

任何可能发生这种情况的想法将不胜感激。

标签: excelvbavariablesms-word

解决方案


推荐阅读