对象变量未分配

时间:2016-08-28 07:38:38

标签: vba

代码:VBA

将字典项目作为变量时遇到问题。

Dim facebook As Object, instagram As Object, twitter As Object, name As Object
name = InputBox("Enter the name of the channel", "Channel")
Dim type_name As String
type_name = InputBox("Enter the type of value you want", "Type")

Set facebook = CreateObject("Scripting.Dictionary")

With facebook

    .comparemode = vbTextCompare
    .Add "brand", 5
    .Add "post", 6
    .Add "likes", 7

End With

Set instagram = CreateObject("Scripting.Dictionary")

With instagram

    .comparemode = vbTextCompare
    .Add "brand", 8
    .Add "post", 9
    .Add "likes", 10

End With

Set twitter = CreateObject("Scripting.Dictionary")

With twitter

    .comparemode = vbTextCompare
    .Add "brand", 11
    .Add "post", 12
    .Add "likes", 13

End With

MsgBox (name & "." & type_name & "=" & name(type_name))

此代码提供错误"对象变量或With Block变量未设置"在输入框之后取值" name"。

1 个答案:

答案 0 :(得分:1)

您已在脚本的第一行为name指定了错误的类型:

Dim facebook As Object, instagram As Object, twitter As Object, name As Object

应该是:

Dim facebook As Object, instagram As Object, twitter As Object, name As String

脚本的最后一行也有错误:

name(type_name)

您似乎期望name同时是字符串和字典对象。对于这种语法,您需要创建另一个字典对象,其中包含“facebook”,“instagram”,“twitter”作为键,并返回您已创建的相应字典的值。所以你得到一个嵌套的结构。

以下是代码:

Dim facebook As Object, instagram As Object, twitter As Object, channels as Object
Dim name As String, type_name As String

name = InputBox("Enter the name of the channel", "Channel")
type_name = InputBox("Enter the type of value you want", "Type")

Set facebook = CreateObject("Scripting.Dictionary")
With facebook
    .comparemode = vbTextCompare
    .Add "brand", 5
    .Add "post", 6
    .Add "likes", 7
End With

Set instagram = CreateObject("Scripting.Dictionary")
With instagram
    .comparemode = vbTextCompare
    .Add "brand", 8
    .Add "post", 9
    .Add "likes", 10
End With

Set twitter = CreateObject("Scripting.Dictionary")
With twitter
    .comparemode = vbTextCompare
    .Add "brand", 11
    .Add "post", 12
    .Add "likes", 13
End With

Set channels = CreateObject("Scripting.Dictionary")
With channels
    .comparemode = vbTextCompare
    .Add "facebook", facebook
    .Add "instagram", instagram
    .Add "twitter", twitter
End With

MsgBox (name & "." & type_name & "=" & channels(name)(type_name))