Excel VBA - Run-Time Error '424': Object Required - vba

I have the following code for a Check Box (ActiveX Control) using Excel 2013:
Private Sub CheckBox1_Click()
If CheckBox1.Value = True Then
CheckBox2.Value = False
Else
CheckBox2.Value = True
End If
End Sub
Private Sub CheckBox2_Click()
If CheckBox2.Value = True Then
CheckBox1.Value = False
Else
CheckBox1.Value = True
End If
End Sub
What it does is simply uncheck Box 2 if I check Box 1, and vice versa. But if I use the above code for a Check Box (Form Control), I get a "Run-time error '424': Object required" error message. Does anyone know of a solution?
UPDATE: The same code above that I tried using in a file that I got from Bytes somehow worked. Since I'm a newbie in VBA, I think I'm gonna have to sit down and study how Excel, Macros & VBA work together. Once I find out the source of the problem (that technically I created myself), I'll post an answer here as to how I figured it out. Thanks to everyone that posted comments & replies. I really appreciate it!

There's a UX (user experience) issue here.
Checkboxes are for when you need the user to pick one or more values.
OptionButtons are for when you need the user to pick one of many mutually exclusive values.
So what you need is OptionButtons (ActiveX controls) - make sure they have the same GroupName, and you'll get the exact same behavior you're trying to achieve, without writing a single line of code:
And then in your VBA code you can access them all by their name (e.g. OptionButton1) to verify their value.
Form controls vs ActiveX controls
"Form Controls" are just shapes that you can assign to a macro (e.g. do something when the user clicks it) - you can't access them and their properties in code like you would with ActiveX controls.
With ActiveX controls you can access them as if they were global object variables, and do what you did:
CheckBox2.Value = True
The biggest hint you get, is IntelliSense: with ActiveX controls, when you type the dot (.) after the control's name, you get a dropdown in the editor, telling you that the VBE understands what you're talking about; when you do the same with a "form control", you don't get that dropdown, and the VBE does NOT understand what you're talking about - and if you persist and run that code, you'll run into run-time errors like you did.

You refer to a Form control by name or index into the Checkboxes collection:
Activesheet.CheckBoxes(1).Value
for example.

You use the incorrect Event listener. Try this
Private Sub CheckBox1_Change()
If CheckBox1 = True Then
CheckBox2 = False
Else
CheckBox2 = True
End If
End Sub
Here is the list event listeners for checkbox

Related

Keeping ComboBox Lists Populated

I have created a Word 2010 VBA Macro Sub with a UserForm. The Sub searches for ==Codes== in a form document, places the found ==code== as a label into the Userform and then allows the user to replace the ==code== with his or her input in the Combobox (part of the same UserForm).
Each string of inputted data is then saved to the Combobox list in the UserForm for later selection if needed.
This works fine until this Macro/Userform expires because a searched document is completed (or cancelled).
I would then like to open the next form document, and in the new launch of this same Macro/Sub retain the former combobox list of data (as options to fill this next opened document - for instance, the code ==Client Name== will come up frequently, and I'd rather select a combobox list entry rather than having to type the client name over and over)
But I can't seem to keep the combobox list in the new launch of this Macro Sub populated with the previous combobox data - even if I isolate this routine as a separate module and pre-define the variables with "Public" dimensions.
So, before I knock myself out trying to figure this out ... just a simple question:
Once a Macro terminates are all of the Public variables "dropped"? When I used to program in DOS WP.51 Macros you could keep data strings in the RAM endlessly (until you "killed" them, or closed WP)
If the Public variable are not "dropped", could someone give me a sample of code by which Public variables could be retained and populated into a duplicately launched combobox userform.
Any ideas, howsoever brief, would help
Thanks much in advance. . .
Mike
Not entirely sure what you're trying to do, but what I'd recommend is the following (Assuming that the form is named, "UserForm1" and then "UserForm2":
1) Create a Module that you use to open the form using:
Sub test()
UserForm1.Show
'Rest of things that you want to do...you will be able to access the values in your combobox in userform1
UserForm2.Show
End Sub
2) In your UserForm1, include a button that will close the form and include the following code:
Sub btn_Exit_Click()
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then
Cancel = True
MsgBox "The X is disabled, please use a button on the form.", vbCritical
End If
End Sub
This will allow you to maintain control of the UserForm and ensure that you can keep the values. It may be possible to disable the Closing button, but I wasn't able to figure it out (my experience with forms is mostly in Access and those have different properties).
Hiding the form keeps the values so that you can look at them whereas when the user closes the form you lose the values that were in it.
*Note: Code to disable the X button taken from VBA Express

How to hide unchecked checkboxes when printing

I am working on creating a contract specification page in Word 2013 with checkboxes so that my boss can click each box that he wants to include in the final printed contract, and hide the ones he doesn't need. I'm completely new to VBA but I know that I need to use it to achieve this. From searching the internet I've used bookmarks and the code below:
Private Sub CheckBox1_Click()
If CheckBox1.Value = False Then
ActiveDocument.Bookmarks("Work1").Range.Font.Hidden = True
Else
ActiveDocument.Bookmarks("Work1").Range.Font.Hidden = False
End If
End Sub
But this code seems to hide the checkboxes before I can click them. I would like the checkboxes to stay visible until they print, in case my boss needs to make a change. I also tried using another code, but it also didn't work the way I wanted it to:
Private Sub CheckBox1_Click()
If CheckBox1.Value = False Then
ActiveDocument.Bookmarks("Work1").Application.Options.PrintHiddenText = False
Else
ActiveDocument.Bookmarks("Work1").Application.Options.PrintHiddenText = True
End If
End Sub
I would also like to make it so there are no gaps where the unused checkboxes would be. Any help would be greatly appreciated!!
I seem to have overcomplicated the issue yesterday. Your only problem was that your checkboxes turn unvisible along with the text. You just need to bookmark exactly the text you want to hide/show leaving the checkbox (perceived by Word as a part of the text) outside of the bookmark.
Your code will do this fine, or you can replace it with this:
Private Sub CheckBox1_Click()
Bookmarks("Work1").Range.Font.Hidden = Not CheckBox1
End Sub
By the way, if you make Word show paragraph marks (Ctrl + *), you will be able to see hidden text.
I would suggest your macros:
a) save the current document (in the temporary folder if you want)
b) delete all unchecked boxes
c) print the document
d) close the document
e) open the file saved in the point a).
Should take a dozen lines of code or so.

Running Macros from Toolbar/Running one macro from another

I am trying to develop a macro for a publisher document. This macro will, when run, show a pop-up allowing the user to select one of three types of clients, and add different bullet points to a text box depending on which option was selected. I'm having two different problems which I suspect are coming from the same source. Problem number one is that I can't get the button on my User Form to run a different macro when the button is clicked. Problem two is that I've added my macros to one of the toolbars, and nothing happens when I click on them. In both cases, it's simply not running the macro. What am I doing wrong?
UserForm1
Private Sub CommandButton1_Click()
Application.Run ("ShapeTest")
End Sub
Private Sub UserForm_Initialize()
With ListBox1
.AddItem ("Federal")
.AddItem ("State")
.AddItem ("Local")
End With
End Sub
ThisDocument
Private Sub GenerateStatement()
UserForm1.Show
End Sub
Private Sub ShapeTest()
MsgBox ("Hello!")
Application.ActiveDocument.Pages(1).Shapes(1).TextFrame.TextRange.InsertAfter`enter code here`(Chr(13) & "My Text")
End Sub
Why are you using Application.Run("ShapeTest") rather than simply ShapeTest?
I don't have enough information to be 100% sure, but the following should work: To make ShapeTest callable from the userform you do two things:
1) Move it from ThisDocument to a general code module (first Insert/Module in the editor).
2) Eliminate the word Private in front of Sub ShapeTest()-- you don't want this to be a private sub since you want code outside of the module to be able to use it.
On edit: Alternatively -- you could keep ShapeTest() where it is in ThisDocument, get rid of the Private qualifier and in the userform code refer to ShapeTest as ThisDocument.ShapeTest. I prefer using the first method since I tend to like to keep as much code as possible in general code modules (reserving things like ThisDocument for event handlers) but OTOH my VBA experience is mostly Excel with a smattering of Word and there might be reasons to keep the code in ThisDocument in Publisher. I don't know Publisher, but a problem that I have run into in Word at times is I have sometimes accidentally put code in the Normal template that I wanted to go in the document's project. If something similar is possible in Publisher you should double check where your code is living.

Userform.Show on a form button will not recognize userform, getting Error 424

I know very little about VBA, but I'm trying to design a userform for an excel workbook. The idea is click the button, bring up the userform, enter info, hit OK, and your info is formatted correctly and inserted into the worksheet.
I have 3 userforms that all work fine, but any macro I create that references one of them just does not recognize that that particular userform exists.
The code I'm having a problem with is pretty straightforward:
Private Sub LiquidFormButton_Click()
LiquidEntryUserform.Show
End Sub
Edit (Update): So I tried making a new userform, with a different name. I copied and pasted all of the controls from the object over to the new userform, changed the name of the macro to bring up the userform, and voila, it works. However, now the userform itself doesn't do anything because none of the controls actually have any codes behind them telling them what to do. That's fine, I'll just copy over the codes from the broken form and BOOM now it doesn't work. Soooo something in the very very simple coding within the userform itself is preventing it from being shown, even though the new userform AND the broken one both, in fact, do everything else they need to do besides show up. I'll post the full userform code up later on after some dabbling. Thank you!
You should 'instantiate' the form like so
Private Sub LiquidFormButton_Click()
Dim liquid as LiquidEntryUserform ' define a liquid var of the correct type
Set liquid = new LiquidEntryUserform ' create the Form
liquid.Show 'show it
' here you can still access variables
' on the form
If liquid.TextBox1.Text = "700" Then
'do things
End if
End Sub
My project looks like this:
You can use the Object Browser (View|Object Browser or hit F2) to find the Forms and Classes you have in your project:
I had a similar experience after making some changes to a UserForm. I noticed something was actually working immediately prior to the 424 error occurring. Using F8 to step thru my code, it turned out I was asking a control to be configured - that I had deleted!!
I was using this code in the MS XL Objects worksheet (the button is on the associated worksheet)...
Private Sub cmdTransactions_Click()
frmTransactions.Show
End Sub
to bring up the UserForm and this code in the Forms module...
Private Sub UserForm_Initialize()
: : :
Row_Number = [mostrecent].Value
Cells(Row_Number + 1, 2).Select <<< this bit was happening (.Select works for me!!)
: : :
cmdReset.Enabled = False <<< a control in the UserForm
chkDeposit.Enabled = False <<< this control had been deleted!! Remarked out but un-Remarked for clarity
: : :
End Sub
Hope that might help someone.

Provide a range selection tool/utility to the user in Excel VBA

I am trying to develop a user form in Excel 2007 VBA and want to provide a user with a range selection icon, something like this:
However, I have not been able to find any built-in form design tool or any online tool which provides this or at least gives me an idea. If anyone has any idea about this, I will greatly appreciate their help.
This control is called RefEdit control.
To use it, you have to first add it to the toolbox window by right-clicking in the toolbox window and selecting Additional Controls.... Then you select RefEdit.Ctrl and close the dialog.
Now you can select it in the toolbox and place it on your form.
Another alternative to using the RefEdit.Ctrl is to hook into some undocumented features of the TextBox control and use the Application.InputBox function.
There are two properties of the TextBox control that do not appear in the Properties dialog, that allow you to add a button on the right. They are DropButtonStyle and ShowDropButtonWhen. When the button is clicked it will fire the DropButtonClick event for the control where you can show the input box.
Start by placing a TextBox control on the form. Then add the following to the UserForm_Initialize procedure:
Private Sub UserForm_Initialize()
txtRefersTo.DropButtonStyle = frmDropButtonStyleReduce
txtRefersTo.ShowDropButtonWhen = frmShowDropButtonWhenAlways
End Sub
Then add an event handler to the DropButtonClick event as follows to capture the range using the Application.InputBox dialog:
Private Sub txtRefersTo_DropButtonClick()
Me.Hide
txtRefersTo.Text = Application.InputBox("Select the range", "Range Picker", txtRefersTo.Text, Type:=8)
Me.Show vbModal
End Sub
The main advantage to this approach is that it allows you to place a control within a frame or on a separate tab without experiencing the issues associated with the RefEdit.Ctrl. The disadvantage is that it requires a separate dialog to interact with Excel.
Although this question is already almost a decade old, it still came up as my first Google search result so I'm going to post an answer as another approach to consider. The InputBox with type set to cell reference might be sufficient for many people's needs. The InputBox type does the drudge work of validating the user's response. See this article for how to use the InputBox types: https://www.thespreadsheetguru.com/blog/vba-to-select-range-with-inputbox
I liked #krey answer which was basically a very simplified version of the link shared in #stifin answer --> https://www.thespreadsheetguru.com/blog/vba-to-select-range-with-inputbox
But both used "odd" names for the buttons and I think guides should use default names/values for easy understand and manipulation by end user. Additionally, I added a CommandButton to "run" the userform and a "select" statement for initial testing. I also wanted to provide an initial value as I try to pre-populate my userforms, but allow end user to override if needed.
Here is the final code snipppets utilizing a UserForm w/ one TextBox named TextBox1 (default) and one CommandButton named CommandButton1 (also default).
Option Explicit
Public rng As Range
Public Sub UserForm_Initialize()
Me.TextBox1.DropButtonStyle = fmDropButtonStyleReduce
Me.TextBox1.ShowDropButtonWhen = fmShowDropButtonWhenAlways
Set rng = Range("A1:B4")
TextBox1.Value = rng.Address(False, False)
End Sub
Public Sub CommandButton1_Click()
rng.Select
Unload Me
End Sub
Public Sub TextBox1_DropButtonClick()
Me.Hide
Set rng = Application.InputBox("Select the range", "Range Picker", TextBox1.Text, Type:=8)
TextBox1.Value = rng.Address(False, False)
Me.Show
End Sub