问题
My task: I have multiple forms in one Word document and it has to be filled out with the same information such as company name, address, tax number, etc.
My experience with VBA is very limited so I used bookmarks and wrote some code:
Private Sub OKbutton_Click()
Dim FirmaName As Range
Set FirmaName = ActiveDocument.Bookmarks("FirmaName").Range
FirmaName.Text = Me.TextBox1.Value
Dim FirmaNameRio As Range
Set FirmaNameRio = ActiveDocument.Bookmarks("FirmaNameRio").Range
FirmaNameRio.Text = Me.TextBox1.Value
Me.Repaint
stinfo.Hide
The issue or challenge for me is, that I want to be able to "dynamically" change the data in the pop-up form. Now it works the way every time I press OK-button, it adds new data behind the previous, which is undesirable. If I make a mistake I want to change it only in the pop-up window, not in the document.
So is there any way to program it that the information typed in the pop-up window can rewrite the previous information?
It´s not necessary to use bookmarks or whatsoever. It just has to work, that it´s easy for other employees to fill out these forms and save some time by skipping mechanical copy-pasting.
回答1:
Use code like:
Sub UpdateBookmark(StrBkMk As String, StrTxt As String)
Dim BkMkRng As Range
With ActiveDocument
If .Bookmarks.Exists(StrBkMk) Then
Set BkMkRng = .Bookmarks(StrBkMk).Range
BkMkRng.Text = StrTxt
.Bookmarks.Add StrBkMk, BkMkRng
End If
End With
Set BkMkRng = Nothing
End Sub
which you would call with code like:
Call UpdateBookmark "FirmaName" Me.TextBox1.Value
And, since you're using bookmarks, instead of writing the same value multiple times to different bookmarks, simply insert a cross-reference to the first bookmark whose value is to be repeated and, when you've updated all the bookmarks, use a single code line to update all the cross-references:
ActiveDocument.Fields.Update
来源:https://stackoverflow.com/questions/61170358/vba-word-filling-out-multiple-forms-with-pop-up-window