Situation:
Whilst writing an answer for a question on SO I got stuck with the following:
Question: How to pass a worksheet property as a variable?
For example, I was looking at worksheet protection properties and wanted to assign them via a variable e.g. with psuedo code:
myVar = ProtectDrawingObjects
If Worksheets("Sheet1").myVar = True Then ......
What I have tried:
1) In the first instance I searched for a set of enums to use but to no avail. I found references in Visual Basic to enums but not the kind of thing I am after. I was looking for something like Activesheet.Protection(1)
.
2) I then tried concatenation (which I expected to see fail) e.g.
If ws & "." & "ProtectDrawingObjects" = False Then MsgBox "False"
Which indeed failed with
Object doesn't support this property or method
3) I tried declaring object/variant variables and assigning values to these resulting in expected Type Mismatch errors or the above property not supported error.
4) I also tried to find similar SO questions such as: Get worksheet property using worksheet variable, but that seemed to imply I would need to create a custom property rather than the access the existing property of the worksheet.
5) As per @TimWilliam's helpful suggestion I tried the CallByName()
function e.g.
Dim result As Boolean
result = CallByName(ws, "ProtectDrawingObjects", VbGet)
This worked well for those properties that commenced with "Protect" e.g. "ProtectDrawingObjects
" but not for any of the properties that commenced with
"Allow" e.g. "AllowFormattingCells"
; which returned:
Object doesn't support this property or method
All the properties are READ
and there clearly is a Get
mechanism as one can do:
If ws.Protection.AllowFormattingCells = False then
Is it simply not exposed via CallByName()
? And is there a workaround?
Overall objective:
I wanted to have the different possible properties of the protection object in an array e.g. ("AllowDeletingColumns", "AllowDeletingRows",......) and then loop to test whether they were set to True
or False
.
I know I can use If
statements to determine the states but I am interested in if there is a way essentially to do the following?
Worksheet.myVar
Where in pseudo code, in a loop, this would be
If Worksheet.myArr(i) = False Then ..Do Something.....