Reputation: 3897
I need to populate my drop-down list from a whole column rather than a named range.
Working code using a named range:
'Populate drop-down list (combo box) from range...
Dim range_b As Range
For Each range_b In Worksheets("2.1 Clients").Range("ClientList")
With Me.cs_ClientName1
.AddItem range_b.Value
.List(.ListCount - 1, 1) = range_b.Offset(0, 1).Value
End With
Next range_b
I've tried various permutations of the For Each
line:
'For Each range_b In Worksheets("2.1 Clients").Columns(4)
'For Each range_b In Worksheets("2.1 Clients").Range(Columns(4))
'For Each range_b In Worksheets("2.1 Clients").Columns("D:D")
...that last of which seems to causing Excel to crash.
Upvotes: 0
Views: 693
Reputation: 6433
It is more sensible to use Named Range instead of fixing it in code. Imagine someone added a column before D! You would have to change all codes that are hard coded. It is also better to put the With block on top of the For loop. You may also need to Clear the list before it.
Just make sure the named range ClientList refers to Worksheets("2.1 Clients").Range("D:D"). If you have done that, use below:
With Me.cs_ClientName1
For Each range_b In ThisWorkbook.Names("ClientList").RefersToRange
If Not IsEmpty(range_b) Then
.AddItem range_b.Value
.List(.ListCount - 1, 1) = range_b.Offset(0, 1).Value
End If
Next range_b
End With
A Better performance can be achieved if:
Code:
' Data Starts right below the Header (Named Range)
Set range_b = ThisWorkbook.Names("ClientList").RefersToRange.Offset(1,0)
With Me.cs_ClientName1
.Clear ' Clear existing data
Do Until IsEmpty(range_b)
.AddItem range_b.Value
.List(.ListCount - 1, 1) = range_b.Offset(0, 1).Value
Set range_b = range_b.Offset(1, 0)
Loop
End With
Set range_b = Nothing
Upvotes: 0
Reputation: 96753
For Each range_b In Worksheets("2.1 Clients").Range("D:D")
RANGE() is happy with a string address.
Edit#1:
Here is a working example:
Sub dural()
Dim range_b As Range
For Each range_b In Worksheets("2.1 Clients").Range("D:D")
If range_b.Value = "good" Then
MsgBox "good found"
Exit Sub
End If
Next range_b
End Sub
Upvotes: 1