如何在默认选择的单词中的宏中选项?

时间:2013-07-17 21:04:17

标签: vba word-vba

我在单词2010中有以下宏。我想在运行宏时预先选择值1(哥本哈根) - 所以它将我的内容控制下拉列表放在哥本哈根预选的文档中。

我该怎么做?:

Sub Cities()
'
' Cities Macro
'
'
Selection.Range.ContentControls.Add (wdContentControlDropdownList)
Selection.ParentContentControl.Title = "Cities"
Selection.ParentContentControl.LockContentControl = False
Selection.ParentContentControl.DropdownListEntries.Add Text:="Copenhagen", Value:="1"
Selection.ParentContentControl.DropdownListEntries.Add Text:="New York", Value:="2"
Selection.ParentContentControl.DropdownListEntries.Add Text:="London", Value:="3"
Selection.ParentContentControl.DropdownListEntries.Add Text:="Paris", Value:="4"
Selection.MoveRight Unit:=wdCharacter, Count:=1
End Sub

提前致谢!

/ Anders H。

2 个答案:

答案 0 :(得分:0)

你学习the documentation了吗?这适用于Word 2013,但它比此页面的2010版本更详细。

Sub Cities()
    '
    ' Cities Macro
    '
    '
    Dim objCC As ContentControl
    Dim objCE As ContentControlListEntry

    Set objCC = Selection.Range.ContentControls.Add(wdContentControlDropdownList)
    With objCC
        .Title = "Cities"
        .LockContentControl = False
        '.DropdownListEntries.Add Text:="Copenhagen", Value:="1"
        Set objCE = .DropdownListEntries.Add("Copenhagen", "1")
        objCE.Select
        'or
        '.DropdownListEntries.Add("Copenhagen", "1").Select

        .DropdownListEntries.Add Text:="New York", Value:="2"
        .DropdownListEntries.Add Text:="London", Value:="3"
        .DropdownListEntries.Add Text:="Paris", Value:="4"
    End With
    'Selection.MoveRight Unit:=wdCharacter, Count:=1
    'Selection is no longer in the document range
End Sub

这使用Select方法选择哥本哈根。但是,它确实意味着选择不再在文档范围内。你可以使用类似的东西:

ActiveDocument.Characters(1).Select

(或其他一百万种方式......)将光标移回文档范围,选择哥本哈根。

答案 1 :(得分:0)

Sub Cities()
'
' Cities Macro
'
'

Selection.TypeText Text:='I learned English with Google translate in "
Dim oldRange as Range
Set oldRange = Selection ' I didn't try this but it should work

Dim objCC As ContentControl

Set objCC = Selection.Range.ContentControls.Add(wdContentControlDropdownList)
With objCC
    .Title = "Cities"
    .LockContentControl = False
    .DropdownListEntries.Add("Copenhagen", "1").Select
    .DropdownListEntries.Add("New York",   "2")
    .DropdownListEntries.Add("London",     "3")
    .DropdownListEntries.Add("Paris",      "4")
End With
Set Selection = oldRange ' didn't try this but should work. We should be back in the document
' or try ActiveDocument.Characters(1).Select followed by a move to the end of the doc.
' or put in a placeholder (text like "zzzxxxzzz"  and then find it) or a bookmark and then use it.
Selection.MoveRight Unit:=wdCharacter, Count:=1 ' didn't try this but should work. If it "falls" back into the content control then try the following:
Selection.TypeText Text:=" on the 2nd of July, 2013."
' if there is an error mark out the last line and check where the selection ends up after MoveRight.

End Sub