Referencing Text Content Controls - vba

I am trying to reference and paste a specified string into a specific Text Content Controls and have been unable to do this properly.
Basically I have gone through and tried a few different things, first being this;
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
SelectContentControlsByTitle("TextBox1").Add.SetPlaceholderText , , "Please make a drop down selection or manually fill out if not applicable"
The above does not work, as every time I exit my content controller combo box it actually recreates the "placeholdertext" multiple times. I need this to only fill the "TextBox1" Content control.
I have also tried doing something like this,
Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
Set CB1 = SelectContentControlsByTitle("TextBox1")
For Each cc In ccs
If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
CB1.Value = "Please make a drop down selection or manually fill out if not applicable"
Due to the type, value is not able to be used like this. This does not work either.
Below is the original way I was doing what I wanted with the Active-X TextBox which does work;
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
If cc.Title = "ComboBox2" And cc.Range.Text = "Choose an item." Then
TextBox2.Value = "Please make a drop down selection or manually fill out if not applicable"
ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS backup" Then
TextBox2.Value = "The TMS installation directory, settings directory and the database was backed up before the update was performed"
ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS installation" Then
TextBox2.Value = "Installation of version 1.17.X.19XXX performed"
ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS update" Then
TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"
ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Tool presetter update" Then
TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"
ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Database generated" Then
TextBox2.Value = "Database structure created with version 1.17.0"
How can I do the above, while using the Text Content Controls?

A better approach would be:
Private Sub Document_ContentControlOnExit(ByVal Ctrl As ContentControl, Cancel As Boolean)
Dim i As Long, StrDetails As String
With Ctrl
If .Title = "ComboBox1" Then
If ShowingPlaceholderText = True Then
StrDetails = ""
Else
For i = 1 To .DropdownListEntries.Count
If .DropdownListEntries(i).Text = .Range.Text Then
StrDetails = .DropdownListEntries(i).Value
Exit For
End If
Next
End If
ActiveDocument.SelectContentControlsByTitle("TextBox1")(1).Range.Text = StrDetails
End If
End With
End Sub
To make this work, simply add your 'conditional' text to each entry's 'Value' property, and make the "TextBox1" content control's placeholder text whatever you want its prompt to be. This way, you don't have to hard-code either the dropdown option or the 'conditional' text in your VBA code. For a practical demonstration, see: https://www.msofficeforums.com/word-vba/16498-multiple-entries-dropdown-lists.html#post46903
PS: You really should get away from the default ActiveX naming conventions and give your content controls meaningful titles.

Try this for setting the text box text:
Sub SetContentcontrolText()
Dim oRange As Range
Dim cc As ContentControl
For Each cc In ActiveDocument.ContentControls
If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
Set oRange = ActiveDocument.SelectContentControlsByTitle("TextBox1")(1).Range
oRange.Text = "Please make a drop down selection or manually fill out if not applicable"
End If
Next
End Sub

Related

vba cannot clear the word ContentControl content

The contentcontrol "contents cannot be edited" checkbox is unchecked, and I use code to set
LockContets = False
, but even so, there is still error "You are not allowed to edit this selection because it is protected"
the code is as follow:
Sub Test()
Dim CC As ContentControl
For Each CC In ActiveDocument.ContentControls
Debug.Print CC.Type
Debug.Print CC.Range.Text
CC.LockContentControl = True
CC.LockContents = False
CC.Range.Text = "" <--error here
Next CC
End Sub
why will this happen? how to solve it?
You cannot clear the text from Dropdown List, CheckBox, or Picture Content Controls, since they don't have an editable text property.
Try something along the lines of:
Sub Test()
Dim CC As ContentControl
For Each CC In ActiveDocument.ContentControls
With CC
.LockContentControl = True
.LockContents = False
Select Case .Type
Case wdContentControlRichText, wdContentControlText, wdContentControlComboBox, wdContentControlDate
.Range.Text = ""
Case wdContentControlDropdownList
.Type = wdContentControlText
.Range.Text = ""
.Type = wdContentControlDropdownList
Case wdContentControlCheckBox: .Checked = False
Case wdContentControlPicture: .Range.InlineShapes(1).Delete
End Select
End With
Next CC
End Sub
There are many type of conent controls all you need is add an if condition to check if content coontrol type is of text
Sub Test()
Dim CC As ContentControl
For Each CC In ActiveDocument.ContentControls
CC.LockContents = False
If CC.Type = wdContentControlRichText Or CC.Type = wdContentControlText Then
CC.Range.Text = ""
End If
Next CC
End Sub

VBA to add a row to the bottom of the table and insert Rich Text Content Control

I have a form in Word 2013. In it are various tables and I want users to be able to add a row to the bottom of the table. I have done this with the following code:
`Dim oTable As table
Dim oCell As Cell
Dim oPrevRow as Row, oNewRow As Row
Dim iColumn As Long
Set oTable = ActiveDocument.tables (1)
Set oPrevRow = oTable.Rows(oTable.Rpws.Count)
oTable.Rows.Add
Set oNewRow = oTable.Rows(oTable.rows.Count)`
What I want is for all 7 cells in that new row to have Rich Text Content Control inserted into them. How do I do this?
The following code will work with a table bookmarked as 'TblBkMk' anywhere in the document body. Comments in the code show how you could test for a particular table instead. Simply add the code to the 'ThisDocument' code module of the document or its template. The macro triggers when you exit the last content control in the table. The code also provides for the document to have 'read-only' or 'filling in forms' protection (add the password to the code where indicated, if you use one)
Private Sub Document_ContentControlOnExit(ByVal CCtrl As ContentControl, Cancel As Boolean)
'The following code conditionally adds a new row, with content controls, to the designated table.
Dim i As Long, j As Long, Prot As Long
Const Pwd As String = "" 'Insert password (if any) here
'Bookmarking the table provides the flexibility of being able to deal with the addition/deletion
' of other tables before the one we want to process.
Const StrBkMk As String = "TblBkMk"
'Exit if we're not in a table - we don't really need this is using a bookmarked table,
' but it's a safeguard against the bookmark having been expanded/moved.
If CCtrl.Range.Information(wdWithInTable) = False Then Exit Sub
With ActiveDocument
If .Bookmarks.Exists(StrBkMk) = False Then
MsgBox "The table bookmark: '" & StrBkMk & "' is missing." & vbCr & _
"Please add it to the relevant table before continuing.", vbExclamation
Exit Sub
End If
End With
With CCtrl
'Check that the Content Control is within our bookmarked table's range.
If .Range.InRange(ActiveDocument.Bookmarks(StrBkMk).Range) = False Then Exit Sub
' One could test for a particular table instead, in which case all the code dealing
' with wdWithInTable & StrBkMk can be deleted. For example:
'If .Range.InRange(ActiveDocument.Tables(1).Range) = False Then Exit Sub
'Get the number of ContentControls in the table
i = .Range.Tables(1).Range.ContentControls.Count
'Get our ContentControl's index # in the table
j = ActiveDocument.Range(.Range.Tables(1).Range.Start, .Range.End).ContentControls.Count
'Check that we're using the last content control
If i <> j Then Exit Sub
End With
'Solicit user input
If MsgBox("Add new row?", vbQuestion + vbYesNo) <> vbYes Then Exit Sub
With ActiveDocument
' Un-protect the document, if applicable
Prot = .ProtectionType
If .ProtectionType <> wdNoProtection Then
Prot = .ProtectionType
.Unprotect Password:=Pwd
End If
With Selection.Tables(1).Rows
'Insert an empty paragraph after our table, then replace it with a replica of the last row
With .Last.Range
.Next.InsertBefore vbCr
.Next.FormattedText = .FormattedText
End With
'Reset all content controls in the new last row
For Each CCtrl In .Last.Range.ContentControls
With CCtrl
If .Type = wdContentControlCheckBox Then .Checked = False
If .Type = wdContentControlRichText Or .Type = wdContentControlText Then .Range.Text = ""
If .Type = wdContentControlDropdownList Then .DropdownListEntries(1).Select
If .Type = wdContentControlComboBox Then .DropdownListEntries(1).Select
If .Type = wdContentControlDate Then .Range.Text = ""
End With
Next
End With
'Update the bookmarked range
.Bookmarks.Add Name:=StrBkMk, Range:=Selection.Tables(1).Range
' Re-protect the document, if applicable
.Protect Type:=Prot, Password:=Pwd
End With
End Sub

Customize word right click menu

I have the following code to customize the right click menu:
Sub CreateMenuItem()
Dim MenuButton As CommandBarButton
With CommandBars("Text") 'Text, Lists and Tables
Set MenuButton = .Controls.Add(msoControlButton)
With MenuButton
.Caption = "Correct"
.Style = msoButtonCaption
.OnAction = "InsertCorrect"
End With
End With
End Sub
It works fine with text and lists, but only partially with tables:
With CommandBars("Tables")
I must select the whole table or a column then it works but not inside a cell. What is the name for the context menu inside a cell or for text inside a table cell?
I made this routine to see al the names of the CommandBars in Word:
Sub ListYourCommandBars()
For Each c In CommandBars
Debug.Print c.Name
Next
End Sub
Good news they are already sorted alphabetically. I found one called Table Cells. I tried it:
With CommandBars("Table Cells")
and it worked. Only thing, a cell or a number of cells must be "wholly selected". That is, the menu-item doesnt show up if you just enter inside the cell, you must select the cell "as a whole" (dunno how to say it better). Hope this helps.
I got it to work inside a table cell by adding the MenuButton to the following Built-In CommandBars: "Text", "Linked Text", "Table Text", "Font Paragraph", "Linked Headings", "Linked Table", "Linked Text", "Lists", "Table Cells", "Table Lists", "Tables", "Tables and Borders", and "Text Box".
I’m not sure which one actually did the trick. Here’s my code:
Private DisableEvents As Boolean
Private Sub UpdateRightClickMenus()
Dim MenuButton As CommandBarButton
Dim CommandBarTypes(100) As String
Dim i As Long
Dim PRChecklistIsSelected As Boolean
Dim CheckListTypeFound As Boolean
PRChecklist = True
ResetRightClickMenus
CommandBarTypes(0) = "Text"
CommandBarTypes(1) = "Linked Text"
CommandBarTypes(2) = "Table Text"
CommandBarTypes(3) = "Font Paragraph"
CommandBarTypes(4) = "Linked Headings"
CommandBarTypes(5) = "Linked Table"
CommandBarTypes(6) = "Linked Text"
CommandBarTypes(7) = "Lists"
CommandBarTypes(8) = "Table Cells"
CommandBarTypes(9) = "Table Lists"
CommandBarTypes(10) = "Tables"
CommandBarTypes(11) = "Tables and Borders"
CommandBarTypes(12) = "Text Box"
Dim cc As ContentControl
Set cc = FindContentControlByTag("ListBox_PR_TR")
If IsNull(cc) Then
DisableEvents = False
Exit Sub
End If
'Find Selected
For i = 1 To cc.DropdownListEntries.Count
If cc.Range.Text = "Product Review" Then
PRChecklistIsSelected = True
CheckListTypeFound = True
Exit For
End If
If cc.Range.Text = "Technical Review" Then
PRChecklistIsSelected = False
CheckListTypeFound = True
Exit For
End If
Next i
If CheckListTypeFound = False Then Exit Sub
For i = 0 To 12
With Application
If PRChecklistIsSelected Then
'Add right-click menu option to set as a Product Review comment
With .CommandBars(CommandBarTypes(i))
Set MenuButton = .Controls.Add(msoControlButton)
With MenuButton
.Caption = "Set as Product Review Comment"
.Style = msoButtonCaption
.OnAction = "Set_as_Product_Review_Comment"
End With
End With
Else
'Add right-click menu option to set as a Tech Review comment
With .CommandBars(CommandBarTypes(i))
Set MenuButton = .Controls.Add(msoControlButton)
With MenuButton
.Caption = "Set as Tech Review Comment"
.Style = msoButtonCaption
.OnAction = "Set_as_Tech_Review_Comment"
End With
End With
End If
End With
Next i
RightClickMenuItemsAdded = True
End Sub
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
If DisableEvents = True Then Exit Sub
Set cc = FindContentControlByTag("ListBox_PR_TR")
If IsNull(cc) Then
ResetRightClickMenus
DisableEvents = False
Exit Sub
End If
If cc.Range.Text = "Technical Review" Then
Find_PR_Style_ReplaceWith_TR_Style
End If
UpdateRightClickMenus
DisableEvents = False
End Sub
Private Sub Find_PR_Style_ReplaceWith_TR_Style()
Set StylePR = ThisDocument.Styles("Product Review Style")
Set StyleTR = ThisDocument.Styles("Technical Review Style")
With ThisDocument.Content.Find
.ClearFormatting
.Style = StylePR
With .Replacement
.ClearFormatting
.Style = StyleTR
End With
.Execute Forward:=True, Replace:=wdReplaceAll, FindText:="", ReplaceWith:=""
End With
End Sub
Private Sub Set_as_Tech_Review_Comment()
Set StyleTR = ThisDocument.Styles("Technical Review Style")
With ThisDocument
Selection.Style = StyleTR
SetCanContinuePreviousList
End With
End Sub
Private Sub Set_as_Product_Review_Comment()
Set StylePR = ThisDocument.Styles("Product Review Style")
With ThisDocument
Selection.Style = StylePR
SetCanContinuePreviousList
End With
End Sub
Private Sub SetCanContinuePreviousList()
Dim lfTemp As ListFormat
Dim intContinue As Integer
Dim oldListNumber As Single
Set lfTemp = Selection.Range.ListFormat
oldListNumber = lfTemp.ListValue
If Not (lfTemp.ListTemplate Is Nothing) Then
intContinue = lfTemp.CanContinuePreviousList( _
ListTemplate:=lfTemp.ListTemplate)
lfTemp.ApplyListTemplate _
ListTemplate:=lfTemp.ListTemplate, _
ContinuePreviousList:=False, _
ApplyTo:=wdListApplyToWholeList
If lfTemp.ListValue = oldListNumber Then
lfTemp.ApplyListTemplate _
ListTemplate:=lfTemp.ListTemplate, _
ContinuePreviousList:=True, _
ApplyTo:=wdListApplyToWholeList
End If
End If
Set lfTemp = Nothing
End Sub
Private Function FindContentControlByTag(Tag As String) As ContentControl
For Each cc In ThisDocument.ContentControls
If cc.Tag = Tag Then
Set FindContentControlByTag = cc
Exit Function
End If
Next
End Function
Private Sub ResetRightClickMenus()
Dim CommandBarTypes(100) As String
Dim i As Long
CommandBarTypes(0) = "Text"
CommandBarTypes(1) = "Linked Text"
CommandBarTypes(2) = "Table Text"
CommandBarTypes(3) = "Font Paragraph"
CommandBarTypes(4) = "Linked Headings"
CommandBarTypes(5) = "Linked Table"
CommandBarTypes(6) = "Linked Text"
CommandBarTypes(7) = "Lists"
CommandBarTypes(8) = "Table Cells"
CommandBarTypes(9) = "Table Lists"
CommandBarTypes(10) = "Tables"
CommandBarTypes(11) = "Tables and Borders"
CommandBarTypes(12) = "Text Box"
For i = 0 To 12
Application.CommandBars(CommandBarTypes(i)).Reset
Next i
RightClickMenuItemsAdded = False
End Sub
Private Sub Document_Open()
UpdateRightClickMenus
End Sub
Private Sub Document_Close()
ResetRightClickMenus
End Sub

How to select specific form control checkboxes in Excel?

I am working in Excel 2010.
I have set up 10 form control checkboxes in my worksheet, and I want to automatically select a certain set of the checkboxes. All previous posts that I have seen on this topic cover selecting all checkboxes or unselecting all checkboxes.
Here is the VBA code from a previous post for unselecting all checkboxes:
Sub clearcheck()
Dim sh As Worksheet For Each sh In Sheets
On Error Resume Next
sh.CheckBoxes.Value = False
On Error GoTo 0 Next sh
End Sub
Here is the updated code based on this chain, but it is still running into a syntactical issue as well as an unidentified sub:
Sub highengagedonline()
Dim cb As CheckBox, sht As Worksheet
Set sht = Worksheets("Graph")
For Each cb In sht.CheckBoxes
If cb.Name = "Check Box 35" or _
cb.Name = "Check Box 36" or _
cb.Name = "Check Box 37" or _
cb.Name = "Check Box 38" or _
cb.Name = "Check Box 39" Then
cb.Value = 1
Else: cb.Value = 0
End If
Next cb
End Sub
Try something along the lines of:
Sub ClearCheck()
Dim cb As CheckBox, sht As Worksheet
Set sht = Worksheets("Sheet1")
For Each cb In sht.CheckBoxes
If cb.Name = "Check Box 1" Then
cb.Value = 1
Else if cb.Name = "Check Box 2" Then
cb.Value = 0
End If
Next cb
End Sub

command button is being renamed

I am having an issue with active x control command buttons being renamed in Word 2007 without the user actually renaming them. I have directly observed the user saving the document with embedded active x controls and the names appear to be okay when they open the document, but when they save the document, they are renamed.
For example, the name property for CommandButton11 will be renamed to CommandButton111. In some cases it appears that 1 is being added to the end of the Command Button Name so 10 becomes 101, while in other cases 1 is being added to the actual value of the command button so say CommandButton10 becomes CommandButton11. The code for the command buttons does not change, but because I reference the names of the individual command buttons within the code, it obviously breaks.
The purpose of the code is to embed an OLE object in the document and place it correctly in a table.
Below is the specific code for the command button:
Private Sub CommandButton10_Click()
wrdTbl = 1
wrdRow = 11
wrdCol = 2
Set obj = CommandButton10
Call buttontransformer
End Sub
Button transformer is as follows:
Private Sub buttontransformer()
If ActiveDocument.Tables(wrdTbl).Cell(wrdRow, wrdCol).Range.Text = Chr(13) & Chr(7) Then
obj.Caption = "Remove File"
Call OLEObjectAdd
Else
ActiveDocument.Tables(wrdTbl).Cell(wrdRow, wrdCol).Select
Selection.EndKey unit:=wdRow, Extend:=wdExtend
Selection.Delete
obj.Caption = "Click to Add File"
ireply = MsgBox("Add another file?", buttons:=vbYesNo, Title:="UPLOAD NEW FILE?")
If ireply = vbYes Then
obj.Caption = "Remove File"
Call OLEObjectAdd
Else
Exit Sub
End If
End If
End Sub
And OleObjectAdd is as follows:
Private Sub OLEObjectAdd()
Dim fd As FileDialog
Dim ofd As Variant
Dim FP As String
Dim FN As String
Dim Ext As String
Dim fType As String
'Selection.MoveRight Unit:=wdCharacter, Count:=1
Set fd = Application.FileDialog(msoFileDialogFilePicker)
ActiveDocument.Tables(wrdTbl).Cell(wrdRow, wrdCol + 1).Select
With fd
.ButtonName = "Select"
.AllowMultiSelect = False
.Filters.Clear
If .Show = -1 Then
For Each ofd In .SelectedItems
FP = ofd
Debug.Print FP
FN = Right(FP, Len(FP) - InStrRev(FP, "\"))
Debug.Print FN
Ext = Right(FP, Len(FP) - InStrRev(FP, "."))
Debug.Print Ext
Next ofd
On Error GoTo 0
Else
Exit Sub
End If
End With
If Ext = "pdf" Then
fType = "adobe.exe"
ElseIf Ext = "doc" Or Ext = "docx" Or Ext = "docm" Then
fType = "word.exe"
ElseIf Ext = "xls" Or Ext = "xlsx" Or Ext = "xlsm" Then
fType = "Excel.exe"
End If
Selection.InlineShapes.AddOLEObject ClassType:=fType, _
fileName:=FP, LinkToFile:=False, _
DisplayAsIcon:=True, IconFileName:= _
fType, IconIndex:=0, IconLabel:= _
FN
Selection.Move unit:=wdCell, Count:=-2
Selection = FN
End Sub
I had done the Microsoft Fixit to address the Active-X broken controls and it works fine on several other computers I have tested this on.
I have searched high and low for an answer and cant seem to find one. Any help would be appreciated.