How to reference an ActiveX ComboBox as an object in VBA - excel

I want to programatically add items to an ActiveX ComboBox.
How do I reference the ComboBox to perform a .additem to it.
I tried:
Dim lstSubsB As ComboBox
Set lstSubsB = ws.ListObjects("lstSubs") ' - << Error occurs here
but it gives a 'Subscript out of Range' error. The combobox, is named 'lstSubs'.
In addition to the solutions provided, I found that the below also works.
Set lstSubsB = Me.lstSubs
With lstSubsB
For x = arrLower To arrUpper
lstSubs.AddItem arrSubs(x)
Next x
End With

Dim objX As Object
Set objX = ws.OLEObjects("lstSubs")

I know this is an old topic, but I just figured it out and thought I'd save some time for the next person. The property you want is "Object", which in this case is a ComboBox type. I'm sure Object type works as well, but strong typing helps with code complete.
' This snippet adds sheet names to a combobox
Dim lstSubsB as ComboBox
Dim Sht As Variant
' The Object property in this case returns a typed ComboBox
Set lstSubsB = ws.OLEObjects("lstSubs").Object
lstSubsB.Clear
For Each Sht In Worksheets
lstSubsB.AddItem Sht.Name
Next

Related

Excel VBA Store PageSetup Object

Is it possible to store a PageSetup object that will be used to set the printing options of a worksheet? I tried with this code but I'm getting an error that says: Object variable or With block variable not set. This is how I'm doing it since I need to setup the settings first from a form and loop through some sheets using the printing settings stored in this object.
Dim curPageSetup As PageSetup
curPageSetup.paperSize = xlPaperA3
If all that you want to do is change the PaperSize for all of the sheets in your book, you can do it like this
Sub SetPaperSize()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.PageSetup.PaperSize = xlPaperA3
Next ws
End Sub
Not necessary to store PageSetup to change its attributes

How can I tick an Excel checkbox from VBA Access

I have opened an Excel file via VBA Access and can read and write in the Excel Cells. How can I tick an Excel Ckeck Box?
My code:
Dim Excel_App As Object
Dim strExcel As String
Set Excel_App = CreateObject("Excel.Application")
Excel_App.Visible = True
Excel_App.Workbooks.Open fready
With Excel_App
.CheckBox3.Value = True 'This line is used in VBA Excel and I need in Access
End With
Checkboxes belong to a specific collection on a specific Worksheet. Which collection this is, depends on the type of control you're looking for.
Your code is written as if the checkbox belonged to the Excel.Application object - that can't work.
First you need to keep a reference to that Workbook object you're opening, so instead of this:
Excel_App.Workbooks.Open fready
You need this:
Dim book As Object ' early-bound: As Excel.Workbook
Set book = Excel_App.Workbooks.Open(fready)
If you don't know which worksheet to find the checkbox on, you'll have to iterate the workbook's Worksheets collection:
Dim sheet As Object ' early-bound: As Excel.Worksheet
For Each sheet In book.Worksheets
'todo
Next
Form Controls
So we're looking for a CheckBox form control. We'll find that in the sheet's Shapes collection, and we'll know we're looking at a form control when its Type is msoFormControl; we'll know that it's a checkbox control when its FormControlType property returns xlCheckBox:
Dim sheet As Object ' early-bound: As Excel.Worksheet
For Each sheet In book.Worksheets
Dim shp As Object ' early-bound: As Excel.Shape
For Each shp In sheet.Shapes
If shp.Type = 8 ' early-bound: msoFormControl
If shp.FormControlType = 1 ' early-bound: xlCheckBox
'todo
End If
End If
Next
Next
So now we know shp is a checkbox form control. The Value is accessible through the ControlFormat object/property, so you can set the value of a checkbox named Check Box 1 (that's the default name) like this:
If shp.Name = "Check Box 1" Then
shp.ControlFormat.Value = 1 'checked
End If
Of course if you already know which specific sheet you're looking for, there's no need to iterate them all.
ActiveX Controls
If the control is an ActiveX control, it's a whole different story; you'll find it in the OLEObjects collection instead, which contains OLEObject instances, which have an Object property that returns the MSForms.CheckBox object; you can get the name of the checkbox from the OLEObject.ShapeRange.Name:
Dim ctrl As Object ' early-bound: As Excel.OLEObject
For Each ctrl In sheet.OLEObjects
If TypeName(ctrl.Object) = "CheckBox" Then ' early-bound: If TypeOf ctrl.Object Is MSForms.CheckBox Then
If ctrl.ShapeRange.Name = "CheckBox1" Then
ctrl.Object.Value = True ' checked
End If
End If
Next
Note that the early-bound TypeOf ctrl.Object Is MSForms.CheckBox check is MUCH more robust than the late-bound TypeName check. You need to reference the MSForms type library through Tools > References to use it (it's already referenced if your VBA project has any UserForm component, in which case early-bound code is a no-brainer).

How to access textBox placed on sheet in VBA module?

I have placed a TextBox control on a sheet in Excel, in a VBA module I want to acces the TextBox and populate with content.
How do I reference the TextBox control?
I've named the TextBox 'tbSQL', in the module I can see Application and can refernece the sheet from the module, the sheet is called 'Database Info.'
I want to write data into the TextBox from the VBA module, but so far I haven't been able to reference it.
I've tried:
Public Const DATABASE_INFO As String = "Database Info."
Dim objDBsheet As Worksheet, objSQL As Range
Dim tbSQL As TextBox
Set objDBsheet = Application.Sheets(DATABASE_INFO)
Set tbSQL = objDBsheet.Shapes("tbSQL")
But this is as far as I get it errors on the Set tbSQL line. The reported error is "Type Mismatch"
I know the control is a TextBox, it was created from the Controlbox toolbar. When looking in the range bar in Excel it displays:
"=EMBED("Forms.TextBox.1","")"
In the Properties box for the TextBox control I have set the (Name) property to tbSQL, however it remains unchanged in the fx text box. It does show as tbSQL in the range box.
Most likely its a bug in Excel. It has nothing to do with Excel-2003.
If you use a Worksheet type variable then Excel fails to discover the control on that sheet in VBA. So if you declare your sheet holding variable as Object / Variant , the code will work fine.
Other alternative is to directly use the Worksheet's CodeName, so if you set the Worksheet's name as wksDBSheet in the VBA IDE's property grid and use that in your code, it will discover the TextBox
Sub test()
Dim objDBsheet As Object 'As Worksheet // Making the 0bjDBSheet type as Object or Variant
'// Allows the discovery of the TextBox on the sheet.
'// Most Likely its a bug.
Dim objSQL As Range
Dim tbSQL As MSForms.TextBox
Set objDBsheet = Application.Worksheets("Database Info.")
Set tbSQL = objDBsheet.tbSQL
tbSQL.Text = "Bug"
'/ Other Alternative is to directly use the CddeName of the sheet.
Set tbSQL = wksDBsheet.tbSQL
tbSQL.Text = "Code Name used"
End Sub
Text Box as shape, or Label as Form Control, or ActiveX control:
Sub f()
Dim tb As Shape, lblControl As Object, lblActiveX As Object
Set tb = Sheet1.Shapes("TextBox 1")
Set lblControl = Sheet1.Shapes("Label 2").OLEFormat.Object
Set lblActiveX = Sheet1.Shapes("Label1").OLEFormat.Object
lblControl.Text = "Form Control"
lblActiveX.Object.Caption = "ActiveX Control"
tb.TextFrame.Characters.Text = "Text Box"
End Sub
You need to use:
Sheets("Sheetname").Shapes("tbSQL").TextFrame.Characters.Text = "Anything you want"
In the end it looks like it is a bug in Excel 2003, I was able to reference the control by using Sheet1.tbSQL instead of going through Application.Sheets.
If you put an ActiveX texbox on a worksheet named "MyTextBox" then you can set it's text in vba like this:
ActiveSheet.MyTextBox.Text = "hi"

Load combobox with range of another sheet

I have one combobox in one sheet named extraçao with a combobox,
and I have written this code:
Sub Validar_Idades()
Dim aba1 As Worksheet
Set aba1 = Sheets("IDADE")
Dim aba2 As Worksheet
Set aba2 = Sheets("EXTRAÇÃO")
aba2.ComboBox1.Clear
aba2.ComboBox1.List = aba1.range("A2:A" & aba1.range("A" & aba1.Rows.Count).End(xlUp).Row).Value
End Sub
Why don't I see combobox1?
There is an important distinction between Worksheet objects and Sheet objects:
Worksheet can contain only data (in cells)
Sheet can contain data, and other objects like Charts, combo boxes, list boxes, etc
To declare a Worksheet variable use Worksheet type
To declare a Sheet variable use its CodeName, that appears before the name in brackets:
.
Try one of the 2 options bellow
Option Explicit
Sub Validar_Idades()
Dim aba1 As Worksheet 'Worksheet contain only data (no objects)
Set aba1 = Worksheets("IDADE")
'To declare a variable of type Sheet you need to use its "CodeName"
Dim aba2 As Sheet2 'Sheet can contain data and other objects
Set aba2 = Sheets("EXTRAÇÃO") 'like ListBoxes, Charts, ComboBoxes, etc
aba2.ComboBox1.Clear
aba2.ComboBox1.List = aba1.Range("A2:A" & _
aba1.Range("A" & aba1.Rows.Count).End(xlUp).Row).Value
End Sub
Sub Validar_Idades2()
'or simply use its code name instead of a variable
Sheet2.ComboBox1.Clear
Sheet2.ComboBox1.List = Sheet1.Range("A2:A" & _
Sheet1.Range("A" & Sheet1.Rows.Count).End(xlUp).Row).Value
End Sub
The Worksheet class does not have a combobox1 property - since of course not every worksheet has that control on it - which is why the compiler objects to your code. In addition to using the codename, as Paul Bica suggested, (though there is no generic Sheet object - each sheet is effectively its own class), you could simply declare your variable as Object rather than Worksheet so the code is late bound and the compiler won't object. Alternatively, you can access the control through the OLEObjects property of the Worksheet class:
aba2.OLEObjects("ComboBox1").Object.List = aba1.Range("A2:A" & _
aba1.Range("A" & aba1.Rows.Count).End(xlUp).Row).Value

I want to know the difference between Sheet1 and setting worksheets

I have a piece of script that’s in module1 that checks if an option button is clicked.
The option button is placed in Sheet1, name “Info”, so I thought the script below would work
Sub checkClicked()
dim Page as worksheet
set Page as worksheets(“Info”)
Debug.print Page.optClicked
End sub
But when I did it like this it says method or data member not found. It would only work if I replace it with
…
Debug.print Sheet1.optClicked
…
Can anyone give me an insight why this happens?
Think of Sheet1 as a "subclass" of "worksheet" - when you add controls to the sheet you're adding new members. A generic worksheet object doesn't have a member which represents your option button, whereas Sheet1 does.
Sub Test()
Dim sht As Worksheet
Dim sht1 As Sheet1
Set sht = ThisWorkbook.Sheets("Sheet1")
Set sht1 = Sheet1
Debug.Print sht.optClicked 'error
Debug.Print sht1.optClicked 'OK
End Sub
Set Page = ActiveWorkbook.Worksheets("Info") should work. I think worksheets is no real property in VBA...
Also, your debug print code looks weird, use debug.print("bla")..
Do you have Option explicit activated?
Try Set Page = Worksheets("Info") and do NOT use these curly “” quotes - just in case (for Excel formulas this DOES matter).
The argument within Worksheets is the name of the worksheet you are interested in, i.e. "Sheet1".
Other approach: the ActiveX controls on sheet are accessible from two collections: Shapes and OLEObjects. You could use the OLEObjects collection to get access to your checkbox.
Sub checkClicked()
Dim Page As Worksheet
Set Page = Worksheets("Info")
' 1/ ActiveX check box in Shapes collection
Dim myShape As Shape
Set myShape = Page.Shapes("optClicked")
' --------------------------------------
' 2/ ActiveX check box in OLEObjects collection
Dim myOLEObject As OLEObject
Set myOLEObject = Page.OLEObjects("optClicked")
' Use Object property to get access to your check box
Dim myCheckBox As Variant
Set myCheckBox = myOLEObject.Object
If (TypeOf myCheckBox Is MSForms.CheckBox) Then
Debug.Print myCheckBox.value
End If
End Sub

Resources