【发布时间】:2017-01-11 16:57:43
【问题描述】:
我已经有一段时间没有编写代码了,而且不是 Visual Basic,所以如果我的问题简单或解释不清,请原谅我。
我有一个 Sub CustomSave(),它验证没有空白的 ContentControls 需要填写,然后 SaveAs 的 (.docm) Word 文档,标题为“用户名”“请求日期”“请求操作”然后删除 { Save }(见下文)和文档中的其他 1 个字段,以防止意外编辑。
当我从 VBA 运行 Sub 时,它可以完美运行。
从字段调用 Sub(不传递任何内容):{MacroButton CustomSave Save}
当我激活所述字段时,我收到此错误:
(标题) Microsoft Visual Basic for Applications [X]
(内容)类型不匹配
(选项)[确定][帮助]
帮助只是将我带到我找不到答案的通用 Microsoft 在线帮助。
我正在重新输入代码,因此请忽略缺少保存目录,如果我在此处出错,请不要假设实际文档中存在拼写错误:
Sub CustomSave()
' Deselect the Save Field
Selection.Collapse
' Set checks for required data
Dim tRequest As Boolean
Dim tUser As Boolean
Dim tOffice As Boolean
Dim tCard As Boolean
tRequest = ActiveDocument.SelectContentControlsByTitle("Request").Item(1).ShowingPlaceholderText
tUser = ActiveDocument.SelectContentControlsByTitle("User").Item(1).ShowingPlaceholde tText
tOffice = ActiveDocument.SelectContentControlsByTitle("Office").Item(1).ShowingPlaceholderText
tCard = ActiveDocument.SelectContentControlsByTitle("Card").Item(1).ShowingPlaceholderText
' Set file name variables
Dim cardHolder As String
Dim cardAction As String
cardHolder = ActiveDocument.SelectContentControlsByTitle("User")(1).Range.Text
cardAction = ActiveDocument.SelectContentControlsByTitle("Request")(1).Range.Text
' Check all and Error out if missing required data
If tRequest Then
Msg = "Action Requested is required."
MsgBox = Msg,,"Error"
Exit Sub
ElseIf tUser Then
Msg = "Username is required."
MsgBox = Msg,,"Error"
Exit Sub
ElseIf ActiveDocument.SelectContentControlsByTitle("Request")(1).Range.Text = "New" Then
' Embedded If to check fields only required for new requests
If tCard Then
Msg = "Card type is required."
MsgBox = Msg,,"Error"
Exit Sub
ElseIf tOffice Then
Msg = "Office location is required."
MsgBox = Msg,,"Error"
Exit Sub
Else
GoTo Save
End If
'If all checks are satisfied, save to the designated location
Else
Save:
' Remove the Save and Clear Fields but not the first Field
Dim rng As Range
For Each rng In ActiveDocument.StoryRanges
With rng.Fields
While .Count > 1
.Item(2).Delete
Wend
End With
Next
' Finally, perform the save
ActiveDocument.SaveAs2 ("Dir" & cardHolder & " " & Format(Now(), "yyyy-mm-dd") & " " & cardAction & ".docm")
End If
End Sub
【问题讨论】:
-
发布子代码。
-
@cyboashu 更新
标签: vba call ms-word type-mismatch