什么对象没有正确设置或引用?

时间:2016-10-12 17:40:53

标签: excel vba excel-vba dictionary

Private Sub UserForm_Initialize()
Call CreateDictFromColumns("Schedule", "A", "B")
Dim dic As Dictionary
Set dic = createdDic
For Each k In dic.Keys
    MsgBox dic(k)
Next
With ListBox1
    .AddItem "test"
End With

End Sub

'http://stackoverflow.com/questions/33523658/what-is-the-easiest-way-to-take-two-columns-of-data-and-convert-to-dictionary
Function CreateDictFromColumns(sheet As String, keyCol As String, valCol As String) As Dictionary
    Dim aDict As Dictionary
    Set aDict = New Dictionary
    Dim rng As Range: Set rng = Sheets(sheet).Range(keyCol & ":" & valCol)
    Dim i As Long
    Dim lastCol As Long '// for non-adjacent ("A:ZZ")
    lastCol = rng.Columns.Count
    For i = 1 To rng.Rows.Count
        If (rng(i, 1).Value = "") Then Exit Function
        aDict.Add rng(i, 1).Value, rng(i, lastCol).Value
    Next
    Set createdDic = aDict
End Function

我不断收到错误" Object Required",我相信它来自Set dic = createdDic但是我似乎无法弄清楚为什么这是错误的。此对象是否需要以这种方式设置,或者在尝试将函数作为字典引用时是否设置不正确?所有这些代码正在尝试创建一个字典作为键作为键,行是存储的值。任何其他注释将有助于更多地了解excel如何工作,以及如何处理声明字典作为函数。感谢。

1 个答案:

答案 0 :(得分:6)

您应始终在模块中使用Option Explicit。这将无法编译未声明变量的代码(通常是印刷错误的情况等)

例如,您有:

Set dic = createdDic

但是,createdDic不是任何现有对象,对象变量或函数的名称,它返回子例程UserForm_Initialize范围内的对象。

这是做什么的,将createdDic解释为Variant类型的未声明变量,默认情况下,它将包含一个空字符串或空数字值,它将表达式计算为:

Set dic = ""  

Set dic = Empty

这会引发 Object Required 错误,因为您正在尝试将非对象分配给对象变量。

可能让你感到困惑,你在这里调用函数(但不返回任何值):

Call CreateDictFromColumns("Schedule", "A", "B")

修复此错误

CreateDictFromColumns的结果分配给dic对象变量,如下所示:

Set dic = CreateDictFromColumns("Schedule", "A", "B")

确保在End Function之前返回值:

Set CreateDictFromColumns = aDict

全部放在一起:

Private Sub UserForm_Initialize()

Dim dic As Dictionary
Set dic = CreateDictFromColumns("Schedule", "A", "B")
For Each k In dic.Keys
    MsgBox dic(k)
Next
With ListBox1
    .AddItem "test"
End With

End Sub

'http://stackoverflow.com/questions/33523658/what-is-the-easiest-way-to-take-two-columns-of-data-and-convert-to-dictionary
Function CreateDictFromColumns(sheet As String, keyCol As String, valCol As String) As Dictionary
    Dim aDict As Dictionary
    Set aDict = New Dictionary
    Dim rng As Range: Set rng = Sheets(sheet).Range(keyCol & ":" & valCol)
    Dim i As Long
    Dim lastCol As Long '// for non-adjacent ("A:ZZ")
    lastCol = rng.Columns.Count
    For i = 1 To rng.Rows.Count
        If (rng(i, 1).Value = "") Then Exit Function
        aDict.Add rng(i, 1).Value, rng(i, lastCol).Value
    Next
    Set CreateDictFromColumns = aDict
End Function