for each error

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm getting a variable not defined error using the following code:

Option Explicit
Private Sub UserForm_Activate()
For Each cell In Range("cpName")
If cell.Value <> "" Then
lstMnemonic.AddItem cell.Value
End If
Next cell
End Sub

The same code works to populate another list box. Why am I getting this
error?
 
The same code works to populate another list box. Why am I getting this

The difference is the "Option Explicit" statement which requires all
variables to be declared.

Try:

Option Explicit
Private Sub UserForm_Activate()
Dim cell As Range
For Each cell In Range("cpName")
If cell.Value <> "" Then
lstMnemonic.AddItem cell.Value
End If
Next cell
End Sub



Regards,
KL
 
YOu have option explicit at the top of your code which means that you have to
declare all of your variables. That by the way is a good thing and maked
debugging a lot easier. To fix the code you need to declare cell as a range
object

Option Explicit
Private Sub UserForm_Activate()
dim cell as range 'Here is the range object declaration
For Each cell In Range("cpName")
If cell.Value <> "" Then
lstMnemonic.AddItem cell.Value
End If
Next cell
End Sub
 
thanks for the reply. I thought I had used option explicit in the other code
as well so it didn't make sense to me that one would give me the error and
the other wouldn't. But as it turns out, I was wrong. I had neglected to
include option explicit. THanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Combining Procedures into Loop 3
Object range failed 1
Dependant ComboBox on a UserForm 1
Save Array in memory 5
Error 28 - Excel vba macro 0
automation error 0
Code not working 3
Remove Item from ListBox1 2

Back
Top