如何在 Word 中计算 VBA?

How to do math in VBA in Word?

随着 2020 年税收季节的临近,我正在尝试在 Word 中创建一个简单的宏,它将接受一些用户输入并填充与刺激检查相关的电子邮件模板以发送给我的客户。实际的宏只是打开一个信息框,其中包含三个用户输入的空格。在该框内,有一个 'OK' 按钮和一个 'Cancel' 按钮。取消按钮只是隐藏框,确定按钮执行以下操作:

Private Sub CommandButton1_Click()
    Dim taxpayerName As Range
    Set taxpayerName = ActiveDocument.Bookmarks("tpName").Range
    taxpayerName.Text = Me.TextBox1.Value
    
    Dim numberOfDep As Range
    Set numberOfDep = ActiveDocument.Bookmarks("numDep").Range
    numberOfDep.Text = Me.TextBox3.Value
    
    Dim numberOfDep1 As Integer
    numberOfDep1 = Me.TextBox3.Value
    
    Dim maritalStatus As Range
    Set maritalStatus = ActiveDocument.Bookmarks("mStatus").Range
    maritalStatus.Text = Me.TextBox2.Value
    
    Dim maritalStatus1 As Range
    Set maritalStatus1 = ActiveDocument.Bookmarks("mStatus1").Range
    maritalStatus1.Text = Me.TextBox2.Value
    
    Dim maritalStatus2 As Range
    Set maritalStatus2 = ActiveDocument.Bookmarks("mStatus2").Range
    maritalStatus2.Text = Me.TextBox2.Value
    
    Me.Repaint
    tpInfo.Hide
    
    Dim amount1 As Integer
        If maritalStatus = "single" Then
        amount1 = 1200
        Else
        amount1 = 2400
        End If
    amount1 = ActiveDocument.Bookmarks("a1").Range
End Sub

我正在尝试检查 'single' 的 maritalStatus 变量,并为第一轮刺激付款分配 amount1 1200 或 2400 的值。然后我想将该值插入到我创建的书签 a1 处的 Word 文档中。但是,我目前在代码的最后一行收到运行时错误 13。

我的最终目标是取 amount1 并将其添加到一个新变量 (depAmount1) 中,该变量将 500 美元乘以受抚养人的数量,该数量应存储在 numberOfDep1 中.因此,一个拥有 1 child 的纳税人总共会产生 1,700 美元。然后,我会为第二轮刺激付款重复代码并稍作调整,最后将两个总数加在一起作为总计。

在此先致谢,如有任何帮助,我们将不胜感激。

如果您的问题的核心是最后一行代码中的错误,我想您可能明白了,因为您正试图将书签中的字符串分配给 amount1 变量,该变量指定为一个整数,我认为您想做相反的事情,将值放入文档中。反转您的代码行应该可以解决问题。

ActiveDocument.Bookmarks("a1").Range = amount1