MS Word VBA:计算 ContentControl 输入的平均值并插入 table 中的书签

MS Word VBA: Calculate average of ContentControl inputs and insert to bookmark in table

我有一个 MS Word 文档,我要求用户在各种 ContentControls 中从 1-5 中选择一个数值来回答几个问题。

我在文档顶部插入了一个名为“计算”的按钮。当用户单击此按钮时,我想取他们输入的平均值并将结果输入到 table 中的书签单元格中。用户输入内容控件被命名为“RTi”,其中 i 运行 从 1 到 20.

Private Sub Calculate_Click()
    Dim TotalRating As Double
    Dim OrgRating As Double
    Dim TeamRating As Double
    Dim StratRating As Double
    Dim PandPRating As Double
    Dim EvidenceRating As Double
    Dim ESGRating As Double
    Dim ODDRatnig As String
    
   ' Average of RT 1 to 4,input to bookmark "TotalRating" as Double
   ' Average of RT 5 to 7, input to bookmark "OrgRating" as Double
   ' Average of RT 8 to 10, input to bookmark "StratRating" as Double
   ' Average of RT 11 to 14, input to bookmark "PandPRating" as Double
   ' Average of RT 15 to 18, input to bookmark "EvidenceRating" as Double
   ' Value of RT 19, input to bookmark "ESGRating" as Double
   ' Value of RT 20, input to bookmark "ODDRating" as String
   

End Sub

我在开始时遇到了一些问题,但已将我希望执行的步骤放在上面。如果有人愿意帮我举一个上面第一个注释掉的部分的例子,显示一个代码,该代码将执行平均或 RT1、RT2、RT3 和 RT4,并将结果输入书签 TotalRating。

例如,假设您有一个 书签 "TotalRating" 的单元格。但是您需要处理所有可能的错误情况(例如,他们没有输入数字,Word 无法正确识别数字,没有带有相关标题的 CC,没有带有正确名称的书签, 单元格中有多个段落等)。如果您对这些事情有任何疑问,请不要在这里问 follow-up 问题。要做的事情就是研究它们,然后如果你无法找到答案,请提出一个新问题并参考这个问题。

' Average of RT 1 to 4,input to bookmark "TotalRating" as Double
Call updateDoubleTotal(ActiveDocument,"RT",1,4,"TotalRating")

Sub updateDoubleTotal(doc As Word.Document, CCTitlePrefix As String, StartNum As Integer, EndNum As Integer, CellName As String)
Dim i As Integer
Dim Total As Double
Total = 0
With doc
  For i = StartNum To EndNum
    Total = Total + CDbl(.SelectContentControlsByTitle(CCTitlePrefix & CStr(i))(1).Range.Text)
  Next
  .Bookmarks(CellName).Range.Paragraphs(1).Range.Text = CStr(Total / (1 + (EndNum - StartNum)))
End With

End Sub