0

背景:专有的兽医软件会生成一个文档,该文档预先填充了包含特定患者数据的合并字段。我感兴趣的领域是重量,但它是一个看起来像“24.5 kg”的字符串(Top_Stat)。

我创建了一个脚本来读取该字段并将其转换为整数。但是我现在想使用这个整数来计算基于动物体重的男性药物剂量。为此创建文档变量,但变量(名称和值)存储在文档中。我至少希望删除该值,但似乎无法使用以下脚本获得结果。

Sub GetWeight()
 ActiveDocument.Variables("WeightInKg").Delete
 WeightInt = ActiveDocument.MailMerge.DataSource.DataFields("Top_Stat").Value

 WeightInt = Replace(WeightInt, " kg", "") 'This removes the superfluous text
 WeightInt = Val(WeightInt) 'This converts the weight into a number (integer)
 
 ActiveDocument.Variables.Add Name:="WeightInKg", Value:=WeightInt 'Add the Word variable
 ActiveDocument.Fields.Update
 
End Sub

我错过了什么?抱歉,我是 VBA 新手。

4

1 回答 1

0

您的代码需要一些错误检查。第一次运行时,文档变量“WeightInKg”不存在,当您删除它时,程序出错。

文档变量,不要与 VBA 混淆子例程变量不是 Word 文档字段,因此除非您有其他原因更新所有字段,否则该代码行是不必要的。

最后,您应该始终声明您的 VBA 子例程变量。

我已经修改了您的代码,但无法完全测试它,因为我没有您的邮件合并数据源……但试一试,看看它现在是否适合您。

Sub AutoOpen()
    Call GetWeight
End Sub


Sub GetWeight()
    Dim WeightIn As Long
    On Error Resume Next
    ActiveDocument.Variables("WeightInKg").Delete
    On Error GoTo ErrHandler
    WeightInt = ActiveDocument.MailMerge.DataSource.DataFields("Top_Stat").Value
    
    WeightInt = Replace(WeightInt, " kg", "") 'This removes the superfluous text
    WeightInt = Val(WeightInt) 'This converts the weight into a number (integer)
    
    ActiveDocument.Variables.Add Name:="WeightInKg", Value:=WeightInt 'Add the Word variable
'    ActiveDocument.Fields.Update
ErrHandler:
    If Err.Number > 0 Then
        MsgBox Err.Number & vbCr & Err.Description, vbCritical
        Err.Clear
    End If
End Sub

这是我要填充的 Word 文档的屏幕截图。 截屏

于 2021-03-08T20:15:56.840 回答