从字段

时间:2017-01-11 16:57:43

标签: vba ms-word call word-vba type-mismatch

我在一段时间内没有编码,然后它不是Visual Basic,所以请原谅我,如果我的问题很简单或解释不清楚。

我有一个Sub CustomSave(),它验证没有空白的ContentControls需要填写,然后SaveAs的(.docm)Word文档标题为“用户名”“请求的日期”“请求操作“然后删除文档中的{保存}(见下文)和另外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

1 个答案:

答案 0 :(得分:0)

我发现我通过将代码放在ThisDocument对象和宏模块下的两个位置来导致错误。我删除了ThisDocument版本并运行了脚本。