1

I want to iterate over several ComboBox objects in the same Worksheet sht:

Dim obj As ComboBox
Dim sht as Worksheet
...
For Each obj In Array(sht.ComboBox1, sht.ComboBox2)
Next obj

Runtime error 424: object required (raised at For Each ...)

I also tried to address the objects by iterating over the names:

Dim s as Variant
Dim obj As ComboBox
Dim sht as Worksheet
...
For Each s In Array("ComboBox1", "ComboBox2")
    obj = CallByName(sht, s, VbGet)
Next s

Runtime error 91: Object variable or With block variable not set. (raised at obj = ...)

  1. What is the correct way?

  2. And why don't these approaches work as I would expect them to?

ascripter
  • 5,665
  • 12
  • 45
  • 68
  • Try it with 'Dim obj as Variant' – freeflow Jun 29 '22 at 13:16
  • @KostasK. your first idea worked actually, thank :) While playing around, I also found a 2nd solution posted below – ascripter Jun 29 '22 at 13:38
  • I don't use CallByName a lot, so I wasn't sure if it will return the object. Thanks for confirming. – Kostas K. Jun 29 '22 at 13:41
  • I think part of the reason it's not working may have something to do with implicit let-coercion of the objects' *default property* (`.Value`); errors 424 and 91 both support this. Try declaring a local object variable and set it to sht.ComboBox1, then use these variables to make the inline array: because of let-coercion mechanism, using sht.ComboBox1 directly is ambiguous: it reads like it refers to the object, but actually refers to one of its properties' value. – Mathieu Guindon Jun 29 '22 at 13:46

1 Answers1

1

Approach 1

Prepending Set as suggested by @KostasK. to the assignment works:

Dim s as Variant
Dim obj As ComboBox
Dim sht as Worksheet
...
For Each s In Array("ComboBox1", "ComboBox2")
    Set obj = CallByName(sht, s, VbGet)
Next s

Approach 2

The ComboBox is part of Worksheet.OLEObjects. In this case obj must be declared as type OLEObject to work (as long as Option Explicit is set)

Dim s as Variant
Dim obj As OLEObject
Dim sht as Worksheet
...
For Each s In Array("ComboBox1", "ComboBox2")
    Set obj = sht.OLEObjects(s)
Next s
ascripter
  • 5,665
  • 12
  • 45
  • 68