对象未定义

时间:2016-09-01 13:38:12

标签: vba

"频道","脸书"," Instagram"和" twitter"是"对象"数据类型

"我"," j"和" k"是"整数"数据类型

" WS"是" Woksheet"数据类型

Set channel = CreateObject("Scripting.Dictionary")

With channel

    .Add "facebook", facebook
    .Add "instagram", instagram
    .Add "twitter", twitter

End With

Set facebook = CreateObject("Scripting.Dictionary")

With facebook

    .Add "brand", 0
    .Add "post", 0
    .Add "likes", 0
    .Add "comments", 0
    .Add "boosted", 0
    .Add "shares", 0

End With

Set instagram = CreateObject("Scripting.Dictionary")

With instagram

    .Add "brand", 0
    .Add "post", 0
    .Add "likes", 0
    .Add "comments", 0

End With

Set twitter = CreateObject("Scripting.Dictionary")

With twitter

    .Add "brand", 0
    .Add "post", 0
    .Add "likes", 0
    .Add "retweets", 0
    .Add "is retweet", 0

End With

For Each ws In Sheets

    For i = 0 To channel.count - 1

        If channel.Keys()(i) = ws.name Then

            Sheets(ws.name).Activate
            emptyCol = WorksheetFunction.CountA(Range("1:1"))
            emptyRow = WorksheetFunction.CountA(Range("A:A"))

            For j = 1 To emptyCol

                For k = 0 To channel(channel.Keys()(i)).count - 1

                    If InStr(Cells(1, j), channel(channel.Keys()(i)).Keys()(k)) <> 0 Then

                        channel(channel.Keys()(i))(channel(channel.Keys()(i))) = j
                        MsgBox channel(channel.Keys()(i)) & "." & channel(channel.Keys()(i)) & "=" & j

                    End If

                Next k

            Next j

        End If

    Next i

Next ws

即将出现的错误是:enter image description here

突出显示以下代码:For k = 0 To channel(channel.Keys()(i)).count - 1

1 个答案:

答案 0 :(得分:0)

您以错误的顺序组装Dictionary个对象。当这段代码运行时......

With channel
    .Add "facebook", facebook
    .Add "instagram", instagram
    .Add "twitter", twitter
End With

... facebookinstagramtwitter未设置为任何内容。我猜他们也没有宣布,所以你要存储空的Variant而不是对象。当您最终创建实际对象时,由于它们存储在Dictionary 中的值,所以它太晚了,因此基础变量只会更改为指向新对象。请参阅Why should I dimension my variables in VBA really?

立即解决方法是重新排序代码的顶部部分,如...

Set facebook = CreateObject("Scripting.Dictionary")
With facebook
    .Add "brand", 0
    .Add "post", 0
    .Add "likes", 0
    .Add "comments", 0
    .Add "boosted", 0
    .Add "shares", 0
End With

Set instagram = CreateObject("Scripting.Dictionary")
With instagram
    .Add "brand", 0
    .Add "post", 0
    .Add "likes", 0
    .Add "comments", 0
End With

Set twitter = CreateObject("Scripting.Dictionary")
With twitter
    .Add "brand", 0
    .Add "post", 0
    .Add "likes", 0
    .Add "retweets", 0
    .Add "is retweet", 0
End With

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

解决方案是添加Option Explicit,确保您的变量被正确声明。