繁体   English   中英

如何在使用模板的 word 文档中创建下拉列表?

[英]How do I create a dropdown list in a word doc that is using a template?

我正在尝试在使用模板生成的 word 文档中创建一个下拉列表(这都是通过单击访问按钮完成的)。 当代码运行时,它停在用于创建下拉列表的行并给出以下错误:

运行时错误“445”:对象不支持此操作

我已将问题缩小到这一行:

设置 doc = oWord.Documents.Add(strWordTemplate)

从“Add()”中删除“strWordTemplate”时,下拉列表似乎没有问题。 不过,这只会给我一个带有下拉菜单的空白文档。 如何在通过模板生成的文档中放置下拉列表?

strWordTemplate 是 Word 日历模板的文件位置。 TemplatePath 是一个全局字符串常量,用于保存单词模板。 理想情况下,我会在日历的每个单元格中放置相同的下拉列表(相同的值),但我想弄清楚如何让模板和下拉列表首先显示在同一个文档中

Public Sub MakeCalendar()
Dim strWordTemplate As String
Dim oWord As Object
Dim doc As Word.Document

    'Open a Word Doc With the Template
    Set oWord = CreateObject("Word.application")
    oWord.Visible = False
    oWord.DisplayAlerts = False

    strWordTemplate = TemplatePath & "Calendar.dot"
    Set doc = oWord.Documents.Add(strWordTemplate) 'template is added here

    doc.ContentControls.Add wdContentControlDropdownList 'having the template added causes this line to fail

    'Show the Word Doc
    oWord.DisplayAlerts = True
    oWord.Visible = True

End Sub

从 excel 中尝试了您的(修改后的)代码,因为我认为自己在 Access 中为零(更准确地说,我曾经从 Access 运行)。 它有效,希望能解决您的问题,如下所示在此处输入图片说明

代码是不言自明的

Public Sub MakeCalendar()
Dim strWordTemplate As String
Dim oWord As Object
Dim doc As Word.Document

Dim TemplatePath As String
Dim Tbl As Table, cl As Cell, Rw As Row
'Modify/Delete to your requirement, but take care that last slash ("\") is in place in the path
'it is the most probable cause of error in your code
'It in first place it failed to open the template, but does not give alerts
'as DisplayAlerts set to false and then gives eroor 424 on next line
TemplatePath = "C:\users\user\desktop\"

    'Open a Word Doc With the Template
    Set oWord = CreateObject("Word.application")
    oWord.Visible = True                     ' modify to your choice
    oWord.DisplayAlerts = True               ' modify to your choice

    strWordTemplate = TemplatePath & "Calendar.dotx"
    Set doc = oWord.Documents.Add(strWordTemplate) 'template is added here
    Set Tbl = doc.Tables(1)                      ' Modify to your requirement

    For Each Rw In doc.Tables(1).Rows
    For Each cl In Rw.Cells
    cl.Range.ContentControls.Add wdContentControlDropdownList
    Next cl
    Next Rw
     ' Or use your original code
    'doc.ContentControls.Add wdContentControlDropdownList 'having the template added causes this line to fail

    'Show the Word Doc
    oWord.DisplayAlerts = True
    oWord.Visible = True

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM