1

我是 vba 的新手,正在开发一个文档,提示用户从组合框列表中选择可变数量的值。选择值后,我想将它们作为文本表单字段按顺序插入到文档本身中。让我向您展示我通常如何尝试使其正常工作。

首先,用户选择值:

 [a]
 [b]
 [c]

并选择“确定”按钮。然后,我尝试将这些选定的值添加到从书签开始的 word 文档中。应插入值“a”,后跟一个空格字符,然后是一个空白文本表单域,然后是两个回车符。最后的结果应该是这样的:

 [bookmark]
 [a]'_'[blank_a]'^p'
 '^p'
 [b]'_'[blank_b]'^p'
 '^p'
 [c]'_'[blank_c]'^p'
 '^p'

其中 [bookmark] 是不可见的书签,'_' 是空格,'^p' 是回车。目前我的代码如下:

 Dim myRange As Range
 Set myRange = ActiveDocument.Range(Start:=ActiveDocument.Bookmarks("START").Range.Start, _
 End:=ActiveDocument.Bookmarks("END").Range.End)

 For i = 1 To NUMBER_OF_RESPONSES
     Selection.FormFields.Add(myRange, wdFieldFormTextInput).Name = "question_" & i
     Selection.FormFields.Add(myRange, wdFieldFormTextInput).Result = "response_" & i
 Next i

当然,没有插入文字空格或回车,因为我还没有弄清楚如何去做。这段代码的结果如下:

 [START][blank_c][c][blank_b][b][blank_a][a][END]

我希望颠倒这个顺序,并插入上述格式。关于如何去做的任何指示?

4

2 回答 2

2

我不确定我是否遗漏了什么,但为什么不依赖简单的段落而不是书签呢?在这里,您有一个代码可以做您想做的事情和任何其他事情(您可以修改段落的范围以执行您希望的复杂操作)。

Dim curRange As Range
Dim start_i As Integer
Dim end_i As Integer
Dim NUMBER_OF_RESPONSES As Integer
NUMBER_OF_RESPONSES = 3
start_i = NUMBER_OF_RESPONSES + 1 '0
end_i = 1 'NUMBER_OF_RESPONSES

Set curParagraph = ActiveDocument.Paragraphs.First

curParagraph.Range.Text = "[START]"
i = start_i
Do
    If (start_i < end_i) Then
        i = i + 1
    Else
        i = i - 1
    End If

    Set curParagraph = curParagraph.Range.Paragraphs.Add
    curParagraph.Range.Text = "[question_" & i & "][" & "response_" & i & "]"
Loop While (i <> end_i)

Set curParagraph = curParagraph.Range.Paragraphs.Add
curParagraph.Range.Text = "[END]"
于 2013-06-13T11:00:07.397 回答
1

Solution

Well now I feel silly for asking the question. The solution was pretty simple.

 ActiveDocument.Bookmarks("START").Select

 For i = 1 To NUMBER_OF_RESPONSES
     Selection.Font.Size = 11
     Selection.Font.Bold = True
     Selection.FormFields.Add(Range:=Selection.Range, Type:=wdFieldFormTextInput) _
         .Name = "question_" & i
     Selection.Font.Bold = False
     Selection.TypeText Text:=" "
     Selection.FormFields.Add(Range:=Selection.Range, Type:=wdFieldFormTextInput) _
         .Name = "response_" & i
     Selection.TypeParagraph
     Selection.TypeParagraph
 Next i

So the real issue was placing the cursor in the right location:

 ActiveDocument.Bookmarks("START").Select

From there I was able to use Selection to insert the desired FormFields and characters.

This link was pretty helpful.

And if you are reading this because you also are new and trying to learn what to do, check out how to record a macro. It's a good first step. Record the macro, view the code it generated, and use that code to guide your own development. Cool.

于 2013-06-13T10:54:31.890 回答