【问题标题】:VBA Word: How to let VBA ignore 1000 separator while calculating formfields?VBA Word:如何让 VBA 在计算表单域时忽略 1000 分隔符?
【发布时间】:2014-10-15 08:37:23
【问题描述】:

我需要你的帮助。我有一个小代码总结了 10 个表单域的值。此表单域的格式设置为 1000 分隔符。我遇到的问题是 VBA 现在将 1.000 之类的值返回为 1。换句话说:1+10+100+1.000=112。如何调整代码以便在计算这些表单域时忽略 1000 分隔符?非常感谢任何帮助!

ActiveDocument.FormFields("voattot").Result = Val(ActiveDocument.FormFields("betvoat1").Result) _
+ Val(ActiveDocument.FormFields("betvoat2").Result) + Val(ActiveDocument.FormFields("betvoat3").Result) _
+ Val(ActiveDocument.FormFields("betvoat4").Result) + Val(ActiveDocument.FormFields("betvoat5").Result) _
+ Val(ActiveDocument.FormFields("betvoat6").Result) + Val(ActiveDocument.FormFields("betvoat7").Result) _
+ Val(ActiveDocument.FormFields("betvoat8").Result) + Val(ActiveDocument.FormFields("betvoat9").Result) _
+ Val(ActiveDocument.FormFields("betvoat10").Result)

【问题讨论】:

    标签: vba form-fields


    【解决方案1】:

    我将创建一个单独的函数来解析表单字段中的结果字符串

    Function GetFieldValue(FieldName as string)
    Dim FF As FormField 
    Dim Result As String
    Dim Value As Double
    
    
    Set FF = ActiveDocument.Formfields(FieldName)'Find the Form Field
    Result = FF.Result                           'Get the Text from the Form Field
    Result = Replace(Result, ",", "")            'Remove any commas
    If Trim(Result) ="" Then
        GetFieldValue= 0                         'Return the numeric valu
    ElseIf Isnumeric(Result) Then
        Value = CDbl(Result)                         'Convert to numeric value
        GetFieldValue= Value                          'Return the numeric value
    Else
        Debug.Print "Not IsNumeric(""" & Result & """)"
        GetFieldValue= 0
    End If
    End Function
    

    然后你可以把你的陈述写成

    ActiveDocument.FormFields("voattot").Result = GetFieldValue("betvoat1") _
    + GetFieldValue("betvoat2") + GetFieldValue("betvoat3") _
    + GetFieldValue("betvoat4") + GetFieldValue("betvoat5") _
    + GetFieldValue("betvoat6") + GetFieldValue("betvoat7") _
    + GetFieldValue("betvoat8") + GetFieldValue("betvoat9") _
    + GetFieldValue("betvoat10")
    

    这也意味着您可以将错误捕获放入您的函数中以处理空值或非数值或缺少表单字段。 是否值得打扰取决于您

    【讨论】:

    • 非常感谢!这看起来很合乎逻辑,但我对 VBA 还是很陌生,而且我以前从未使用过 Functions,我无法让它工作。我已经尝试了几件事,但对我来说最合乎逻辑的似乎是通过这个计算将函数与子分开。当我运行脚本时,它不断给我错误:“编译错误:未定义子或函数。”我在这里做错了什么?
    • 明确一点:我必须在 Sub 中运行计算,因为我希望代码在同一个 Sub 中的其他一些代码之后运行。
    • 把函数定义放在Sub定义之外。该函数将作为 Sub 的一部分进行评估。
    • 那行不通。它给出了与我上面提到的相同的错误消息:(
    • 噢!我在定义中将其称为“GetFieldVal”,在子正文中将其称为“GetFieldValue”。难怪它找不到以该名称定义的函数。我将编辑我的答案以纠正该问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多