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:You need this:
If you don't know which worksheet to find the checkbox on, you'll have to iterate the workbook's
Worksheets
collection:Form Controls
So we're looking for a
CheckBox
form control. We'll find that in the sheet'sShapes
collection, and we'll know we're looking at a form control when itsType
ismsoFormControl
; we'll know that it's a checkbox control when itsFormControlType
property returnsxlCheckBox
:So now we know
shp
is a checkbox form control. TheValue
is accessible through theControlFormat
object/property, so you can set the value of a checkbox namedCheck Box 1
(that's the default name) like this: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 containsOLEObject
instances, which have anObject
property that returns theMSForms.CheckBox
object; you can get the name of the checkbox from theOLEObject.ShapeRange.Name
:Note that the early-bound
TypeOf ctrl.Object Is MSForms.CheckBox
check is MUCH more robust than the late-boundTypeName
check. You need to reference the MSForms type library through Tools > References to use it (it's already referenced if your VBA project has anyUserForm
component, in which case early-bound code is a no-brainer).