我正在使用 Word 2007。我创建了一个启用宏的模板,我正在尝试根据用户窗体中文本框的输入自动执行 .SaveAs。如何调暗并设置要在文件名中使用的输入文本?
Sub AutoNew()
frmCustName.Show
Dim Cust As String
Cust = txtInput
ActiveDocument.SaveAs FileName:="MyPath" & Cust & ".docm"
End Sub
这是我的用户窗体宏。
我的用户表单 =“frmCustName”
我的文本框=“txtInput”
我的命令按钮 =“cmdName”
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
我是个新手,此时我的大脑已经完全烧焦了。
您应该使用内容控件而不是书签。 当您更改书签的文本时,书签将被删除。内容控制则不然。
在文档中添加内容控件并为其命名。然后您可以像这样设置内容控制文本(将此代码放入 CommandButton1_Click 事件中,当用户按下按钮时,它将以新名称保存您的文件):
Private Sub CommandButton1_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
Dim CC_text As String
If TextBox1.Text = "" Then 'check if user filled textbox1 first
MsgBox "remider for the user to fill textbox1", vbInformation + vbOKOnly, "ATTENTION"
Exit Sub
End If
'Then you need to push that text in your filename
folder = "D:\Документы Оля\Тест"
CC_text = aDoc.SelectContentControlsByTitle("CName1").Item(1).Range.Text
aDoc.SaveAs2 folder & "\" & "fixed part of your filename" & CC_text & ".docm", FileFormat:=wdFormatFlatXMLMacroEnabled
End Sub