Excel VBA Object Variable or with variable not set

Hi
I get the error "Object Variable or with variable not set" at the line marked 'xxxxxx
I am trying trying to loop through the list created in UniqueList
Sub Test()
Dim dic As Object
Set dic = CreateObject("Scripting.Dictionary")
dic = UniqueList(Range("C2:C12000")) 'xxxxxx

For Each Key In dic.Keys
    MsgBox "Key: " & Key & " Value: " & dic(Key)
Next
End Sub

Public Function UniqueList(rngInput As Range) As Variant
   Dim rngCell           As Range
   Dim dic           As Object
   Dim lngRow            As Long

   Set dic = CreateObject("Scripting.Dictionary")
   
   For Each rngCell In rngInput.Cells
      If Len(rngCell.Value) <> 0 Then dic(CStr(rngCell.Value)) = Empty
    Next rngCell
   UniqueList = dic.Keys
End Function

Open in new window


Prior related question: http:Q_28643756.html
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAsked:
Who is Participating?
 
aikimarkCommented:
Since the UniqueList() function returns an array, use this version of the Test() routine:
Option Explicit


Sub Test()

Dim vKeys As Variant
Dim vItem as Variant
vKeys = UniqueList(Range("C2:C12000"))

For Each vItem In vKeys
    MsgBox "Key: " & vItem
Next
End Sub

Open in new window

0
 
Ken ButtersCommented:
whenever you assign something to an object you always have to use the word "Set".

You have this line of code :

dic = UniqueList(Range("C2:C12000")) 'xxxxxx

"dic" is declared as an object, so to assign an object to it... you must prefix the assignment with "Set".

Correction shown below.

Sub Test()
Dim dic As Object
Set dic = CreateObject("Scripting.Dictionary")
Set dic = UniqueList(Range("C2:C12000")) 'xxxxxx

For Each Key In dic.Keys
    MsgBox "Key: " & Key & " Value: " & dic(Key)
Next
End Sub

Public Function UniqueList(rngInput As Range) As Variant
   Dim rngCell           As Range
   Dim dic           As Object
   Dim lngRow            As Long

   Set dic = CreateObject("Scripting.Dictionary")
   
   For Each rngCell In rngInput.Cells
      If Len(rngCell.Value) <> 0 Then dic(CStr(rngCell.Value)) = Empty
    Next rngCell
   UniqueList = dic.Keys
End Function

Open in new window

0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
That worked well. Thanks very much
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.