vbams-wordbookmarkscontentcontrol

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


I have an MS Word document where I require users to pick a numerical value from 1-5, in various ContentControls for several questions.

I have inserted at the top of the doc a button named Calculate. When users click this button I want to take an average of their inputs and enter the result in to a bookmarked cell in a table. The user input content controls are named "RTi", with i running from 1 to 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

I am having some trouble getting started, but have put the steps above that I wish to execute. If someone would kindly help me with an example for the first commented out section above, showing a code that will perform an average or RT1, RT2, RT3 and RT4 and enter the result in bookmark TotalRating.


Solution

  • For example, assuming you have a cell bookmarked as "TotalRating" . But you will need to deal with all the possible error conditions (e.g., they don't enter a number, the numbers aren't correctly recognized by Word, there are no CCs with the relevant Titles, there is no bookmark with the correct name, there is more than one paragraph in the cell, etc. etc.). If you have questions about any of those things please don't ask follow-up questions here. The thing to do is research them, then if you cannot work out an answer, ask a new Question and reference this one.

    ' 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