check a checkbox in word using vb.net - vb.net

I have a word doc with several checkbox fields. I can fill the text fields, but haven't figured out how to check checkboxes.
I can't just make a macro in word and see how word does it because to use the keyboard to check the box (space bar), you have to enable document protection, which disables macro creation.

I just tried setting an old fashion Word2003 Checkbox with VBA. Worked with that piece of code:
' demo purposes - added a command
Private Sub CommandButton1_Click()
' FormFields refers to Word2003 FormFields
If ActiveDocument.FormFields(1).Type = wdFieldFormCheckBox Then
ActiveDocument.FormFields(1).CheckBox.Value = True
End If
' ContentControls refers to >= Word2007 Controls - thx to StevenDotNet for the hint
ActiveDocument.ContentControls(1).Checked = True
End Sub
On the other hand I created a VS2012 WordProject with VB.net and added some code to check the box on load.
Private Sub ThisDocument_Open() Handles Me.Open
Me.FormFields(1).CheckBox.Value = True
End Sub

Each checkbox has a Value property. You can set this property to True or False to check or uncheck the checkbox.
EDIT
I wrote a little macro that ticks all boxes in the active document. You can edit it to suit your needs. VBA is really nasty though, it took me around 15 minutes to figure this out.
Sub CheckAllBoxes()
Dim ctrl As ContentControl
For Each ctrl In ActiveDocument.ContentControls
If ctrl.Type = wdContentControlCheckBox Then
ctrl.Checked = True
End If
Next
End Sub

Related

Textbox Exit Event for unknown Textbox

I am working on a userform which contains numerous (an unknown number) of textbox controls. The number of textboxes on the form is based on certain parameters being met elsewhere within the project.
The number of textboxes on the form could get up to 100 or so and my users are expected to fill in each of them. However, in many cases the value for one textbox will be the same as the textbox positioned directly above it.
I therefore wish to implement functionality to allow the user to enter a "." followed by tabbing out of the field in order to copy the value from the textbox above it.
There are a couple of ways I could go about this initial requirement:
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox2.Value = "." Then
TextBox2.Value = TextBox1.Value
End If
End Sub
This works absolutely fine.. however given that there is no indication here that the textbox2 is below textbox1 (Other than me knowing where I put it) we could do something like:
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox2.Left = TextBox1.Left And TextBox2.Value = "." Then
TextBox2.Value = TextBox1.Value
End If
End Sub
And again this works absolutely fine.
My problem is this, with up to 100 textbox controls I do not particularly want to write and maintain an Exit event for each possible textbox control.
I will probably phrase this incorrectly, but is there a way to trigger the exit event dynamically by passing the name of the textbox the user has tabbed out of?
Or am I lumbered within dozens of identical subs handling the exit of each textbox specifically?
EDIT:
Reading the post linked from Word Nerd, I have the following included with the userform initialize event
Dim tbCollection As Collection
Private Sub UserForm_Initialize()
Dim Ctrl As MSForms.Control
Dim obj As clsTextBox
Set tbCollection = New Collection
For Each Ctrl In usfEnterTime.Controls
If TypeOf Ctrl Is MSForms.TextBox Then
Set obj = New clsTextBox
Set obj.Control = Ctrl
tbCollection.Add obj
End If
Next Ctrl
Set obj = Nothing
Then we have the class module clsTextBox
Private WithEvents MyTextBox As MSForms.TextBox
Public Property Set Control(tb As MSForms.TextBox)
Set MyTextBox = tb
End Property
Private Sub MyTextBox_Change()
If MyTextBox.Value = ". " Then
If MyTextBox.Top = 24 Then
MsgBox "Nothing to copy from"
MyTextBox.Value = ""
Exit Sub
Else
For Each Ctrl In usfEnterTime.Controls
If Ctrl.Left = MyTextBox.Left And Ctrl.Top = MyTextBox.Top - 18 Then
MyTextBox.Value = Ctrl.Value
Application.SendKeys "{TAB}"
Exit Sub
End If
Next Ctrl
End If
Else
Exit Sub
End If
End Sub
My initial requirement was to use the EXIT event to implement a "." + TAB out of textbox to copy from above, however it appears the TextBox control does not have the EXIT event available. So I am using the change event, application.sendkeys and expecting my users to use ". " (Note blank space) to mimic the same functionality and tab to the next textbox in the tab order index using the spacebar instead. As you can see I am simply looping through all controls and checking the relative TOP and LEFT positions to determine which textbox to copy from. 24 is the position of the top most textbox control and so I am capturing this and displaying a msgbox to advise the user there will be nothing to copy from. -18 represents the gap between the tops of two textbox controls.
Working perfectly, thanks to Word Nerd for linking through to the other post.

Excel - Change BackColor of UserForm TextBoxes and ComboBoxes with VBA

I am just learning VBA and have used some code from an older book (Excel 2010). It could be that Excel 2016 had some changes that make this code not work anymore.
I do not get a compile error for the class or the Subs. The behavior is that NOTHING happens. What is supposed to happen is that the BackColor of either a ComboBox or a TextBox should change color as if is in focus or leaves focus.
As I said, for some reason when I run the code nothing happens. No errors or warnings appear so it's as if the code is running and then just doing nothing.
Here is my code. The comments should make it clear. I am hoping someone can explain to me what is going on and why this code results in no color changes as the focus changes when I tab through the UserForm.
This first block of code is a stand alone Class Module called "clsCtlColor"
Public Event GetFocus()
Public Event LostFucus(ByVal strCtrl As String)
Private strPreCtr As String
'Base Class for chaging Backcolor of ComBoxes and TextBoxes when focus is changed.
Public Sub CheckActiveCtrl(objForm As MSForms.UserForm)
With objForm
If TypeName(.ActiveControl) = "ComboBox" Or _
TypeName(.ActiveControl) = "TextBox" Then
strPreCtr = .ActiveControl.Name
'On Error GoTo Terminate
Do
DoEvents
If .ActiveControl.Name <> strPreCtr Then
If TypeName(.ActiveControl) = "ComboBox" Or _
TypeName(.ActiveControl) = "TextBox" Then
RaiseEvent LostFucus(strPreCtr)
strPreCtr = .ActiveControl.Name
RaiseEvent GetFocus
End If
End If
Loop
End If
End With
Terminate:
Exit Sub
End Sub
The following Subs are in the UserForm Code
Option Explicit
Private WithEvents objForm As clsCtlColor
'*********************************************************************************************************************
'*Subs for managing the BackColor of comboxes and TextBoxes depending on focus.***************************************
'*********************************************************************************************************************
'initializes the Userform with the clsCtlColor class
Private Sub UserForm_Initialize()
Set objForm = New clsCtlColor
End Sub
'Changes the BackColor of the Active Control when the form is activated.
Private Sub UserForm_Activate()
If TypeName(ActiveControl) = "ComboBox" Or _
TypeName(ActiveControl) = "TextBox" Then
ActiveControl.BackColor = &H99FF33
End If
objForm.CheckActiveCtrl Me
End Sub
'Changes the BackColor of the Active Control when it gets the focus.
Private Sub objForm_GetFocus()
ActiveControl.BackColor = &H99FF33
End Sub
'Changes the BackColor back to white when the control loses focus.
Private Sub objForm_LostFocus(ByVal strCtrl As String)
Me.Controls(strCtrl).BackColor = &HFFFFFF
End Sub
'Clears the objForm when the form is closed.
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Set objForm = Nothing
End Sub
In the Class Module the is an On Error Statement that terminates the Sub when an error occurs. However, I commented it out and still, I see no compile errors. So, I can only conclude it is a runtime issue.
Any help would be much appreciated.
UPDATE:
If I use these two subs on a TextBox I get the effect I'm looking for:
Private Sub TextBox1_Enter()
TextBox1.BackColor = RGB(153, 255, 51)
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
TextBox1.BackColor = RGB(255, 255, 255)
End Sub
What I hate about this is that my UserForm has over one hundred TextBoxes and I would need to write these two subs for each TextBox - so like 200++ Subs!
I am still trying to get the above more general approach to work.
One thing I noticed is that if I change the RGB values in the two subs above to Hex values, they no longer work. I tried changing the hex color values in the more general approach to RGB but it made no difference.
Yet Another Update:
It was pointed out that I had a typo in the class LostFucus. I changed that in two places to LostFocus. However, the code still does not work. Then the question was whether or not my code is in the userform module. It is. Then I tried an experiment. I created a new Workbook and imported the code into a brand new class and userform. I added three textboxes. Abracadabra! It worked! However, it does not work in the form I want it to work in. I have scoured the properties for the form itself and the text boxes and I can see nothing different between my form and the dummy form.
This must be something very simple I am over looking!
After a great deal of head scratching and screaming at my poor monitor I finally found the solution but as of now, I am totally disappointed in Microsoft for the weirdness of working with UserForms. Here is what fixed the problem:
I had not yet set the tab order!
I realized the tab order had my form opening with the first tab stop being set for a TextBox in a MultiPage on my form. I set the tab order so that the first TextBox is active on the UserForm and everything works with the coloring on the main body of the form.
Here is where the weirdness begins, in my opinion.
When the last TextBox on the main body of the form is reached and tab is pressed, the multi-page itself is selected. Only after you hit tab a second time is the first TextBox within the MultiPage selected and then the colors are not applied as they are in the main body of the form at all. The same scenario holds true for Frames as well. Also, there does not appear to be a good way to simply tab from the end of page 1 to the beginning of page 2.
It's very disappointing to me because I would have thought that this is not the way it is. I ASSUMED I could set up 1000 TextBoxes, use the Frames and the Multipage to organize things (SO I COULD MAINTAIN THE WINDOW AT ONE SIZE AND NOT HAVE TO SCROLL THE FORM UP AND DOWN) and then set a tab order that would navigate ALL of the TextBoxes regardless of what organizing container they are in. I assumed it would be this way because it MAKES SENSE! I want to click into the first TextBox and simply never touch my mouse until the form is completely filled out. Otherwise, there really is no point in this effort of making a UserForm! I could point and click around in the spreadsheet without the hassle of designing a form and writing code!
What a bummer!
I suppose I can "make it so!" by writing a bunch of code to jump the selection from container to container...MICROSOFT - It should not be this wonky and stupid!

open a sheet checkbox is checked with vba excel

how I can check if a checkbox is selected ?
And after selecting a checkbox for example "a" (in my example) I want to open a excel sheet.
How can I solve this problem?
Thank you all.
In the UserForm module you can just place the following code, when your CheckBox is named "CheckBox1":
Private Sub CheckBox1_Click()
If Me.CheckBox1.Value = True Then
Worksheets("Sheet1").Visible = True
Else
Worksheets("Sheet1").Visible = False
End If
End Sub
This will make "Sheet1" visible when it's checked and invisible when unchecked.
If you name your checkbox differently, you'll see that if you double click the checkbox in the Userform Design, the VBE will already come up with
Private Sub CheckBoxName_Click()
End Sub

Initializing a userform with preset values?

Working in VBA for excel 2010. This is my first time working with VBA and userforms. Right now I have a barebones userform "UserForm1" trying to sort this issue out. It consists of two radio buttons "OptionButton1" and "OptionButton2" belonging to GroupName "WK" and two textboxes "TextBox1" and "TextBox2".
When I run the userform, I want "OptionButton1" to be selected and the subsequent if/then statements to be run. However, right now I cannot get it to do this. My code:
Public Sub UserForm1_Initialize()
UserForm1.Show
Me.OptionButton1.Value = False
Me.OptionButton1.Value = True
MsgBox ("dia locked")
Me.TextBox1.Value = "blah"
End Sub
Public Sub UserForm1_Activate()
End Sub
Public Sub OptionButton1_Click()
If Me.OptionButton1.Value = True Then
MsgBox ("dia locked")
Me.TextBox1.Value = "blah"
End If
End Sub
Private Sub TextBox1_Change()
End Sub
When I run the form, nothing happens and "OptionButton1" is false. If I click it, the message box displays and the textbox displays the text. It just won't do it on startup. I have tried going into the optionbutton properties and setting 'value' to true, which makes it true on startup, but the messagebox still doesn't display and the textbox is blank until I click it.
...please help. Thank you.
I figured it out.
I suddenly found the dropdowns. Apparently I should have put Userform_Initialize() instead of UserForm1_Initialize(), and instead of OptionButton1_Click() I put the code into OptionButton1_Change() which ran the subsequent initialization sequence.
You guys/gals are awesomesauce. I have learned everything from reading your threads. Thank you!

Clear textbox within multi-page userform when textbox is clicked on

I'm having a slight problem with some VBA coding on a multi-page userform I'm creating. I have some textboxes on each page of the userform, and I had code that I had been using with regular userforms to clear the textboxes provided in the following answer to another thread (https://stackoverflow.com/a/8921247/2477891)
The code looks like this:
Sub TB_enter(TB_name)
If Len(Me.Controls(TB_name).Tag) = 0 Then
Me.Controls(TB_name).Tag = Me.Controls(TB_name).Value
Me.Controls(TB_name).Value = vbNullString
End If
End Sub
Sub TB_exit(TB_name)
'When you click out of the textbox and no information has been entered, returns original text
If Len(Me.Controls(TB_name).Value) = 0 Then
Me.Controls(TB_name).Value = Me.Controls(TB_name).Tag
Me.Controls(TB_name).Tag = vbNullString
End If
End Sub
Along with the following code used for the textboxes to clear them:
Private Sub AdNtbx_Enter()
TB_enter ActiveControl.Name
End Sub
Private Sub AdNtbx_Exit(ByVal Cancel As MSForms.ReturnBoolean)
TB_exit ActiveControl.Name
End Sub
My problem is that they are no longer working because they are on multi-pages, and the following line comes up with an error:
Me.Controls(TB_name).Value = vbNullString
Does anyone have any suggestions as to what could be the problem/solution?
I'd really appreciate it.
Thanks!
I believe this is what you are looking for :
Set Page1 = ThisWorkbook.VBProject.VBComponents("UserForm1").Designer.Controls("Multipage1").Pages("Page1")
Page1.textbox1.Text = vbNullString
You can edit ThisWorkbook, UserForm1 etc.. properties to suit your needs, but with this code you will be able clear textboxes on multipage object