在 Word 2007 中,我创建了一个启用宏的模板,该模板使用带有各种计算/公式的表单字段。我正在尝试根据用户窗体中文本框的输入以及单击命令按钮来自动化
.SaveAs
。
如何调暗并设置要在文件名中使用的输入文本?
我有额外的代码来创建发票号码,我将其提取到文件名中并且有效。我只是在如何存储用户窗体文本框中的输入文本方面遇到问题,以便我可以在我的 AutoNew 子例程中使用。
Sub AutoNew()
frmCustName.Show
Dim Cust As String
Dim RA as String
RA = ActiveDocument.Bookmarks("RntlAgrNO").Range.Text
Cust = txtInput
ActiveDocument.SaveAs FileName:="C:\MyPath\" & RA & Cust & ".docm"
End Sub
这是我的用户窗体宏。
这会将输入文本填充到我的表单中的两个书签中。如何存储这个 txtInput 以便我可以在 AutoNew 代码中调用它?
Private Sub cmdName_Click()
Dim BK As String
BK = txtInput
Dim NameBK1 As Range
Set NameBK1 = ActiveDocument.Bookmarks("CName1").Range
NameBK1.Text = BK
Dim NameBK2 As Range
Set NameBK2 = ActiveDocument.Bookmarks("CName2").Range
NameBK2.Text = BK
frmCustName.Hide
End Sub
您应该使用内容控件而不是书签。 当您更改书签的文本时,书签将被删除。内容控制则不然。
在文档中添加内容控件并将其命名为“CName1”。然后你可以像这样设置内容控制文本
aDoc.SelectContentControlsByTitle("CName1").Item(1).Range.Text = txtInput.Text
但是您实际上并不需要存储 txtInput 文本。这是我的代码。将其放入 cmdName_Click 事件中,当用户在填写 txtInput 后按下按钮时,它将以新名称保存您的文件:
Private Sub cmdName_Click() 'put command button in your userform
Dim aDoc As Document 'you can also declare it as Public variable in a module
Set aDoc = ActiveDocument
Dim folder As String
If txtInput.Text = "" Then 'check if user filled txtInput first
MsgBox "remider for the user to fill txtInput", vbInformation + vbOKOnly, "ATTENTION"
Exit Sub
End If
'Then you need to push that text in your filename
folder = "D:\Документы Оля\Тест"
aDoc.SelectContentControlsByTitle("CName1").Item(1).Range.Text = txtInput.Text 'in case you want to store txtInput value, but in my code you don't need it
aDoc.SaveAs2 folder & "\" & "fixed part of your filename" & txtInput.Text & ".docm"
End Sub
如果您仍然想使用书签,请将这些书签放入内容控件“CC_values”中,该书签无法删除并被锁定。然后隐藏CC_values内容控件(将字体属性更改为隐藏)。之后,将下面的过程放入模块中,并在需要重写书签文本时调用它(它存储书签的范围,然后更改该范围中的文本,并向该范围添加同名的书签):
Sub Set_Bookmark_Range_Value(ByRef pBMName As String, pText As String)
Dim aDoc As Document
Set aDoc = ActiveDocument
aDoc.SelectContentControlsByTitle("CC_values").Item(1).LockContents = False 'unlocking content control that stores bookmarks assigned to userform controls
'to change bookmark text (bookmark name = pBMName)
Dim oRng As Word.Range
If aDoc.Bookmarks.Exists(pBMName) Then
Set oRng = aDoc.Bookmarks(pBMName).Range
oRng.Text = pText
aDoc.Bookmarks.Add pBMName, oRng
Else
MsgBox "Bookmark " & pBMName & " doesn't exist.", vbCritical + vbOKOnly, "DELETED BOOKMARK"
End If
aDoc.SelectContentControlsByTitle("CC_values").Item(1).LockContents = True 'locking content control that stores bookmarks assigned to userform controls
lbl_Exit:
Exit Sub
End Sub