Write VBA Dictionary to text file

2019-08-29 17:12发布

I have the twitter search api results stored as an Excel VBA Dictionary. I would like to write the dictionary to a text file. How do I do that?

2条回答
唯我独甜
2楼-- · 2019-08-29 17:46

Consider:

Sub Lexicon()
    Dim d As Dictionary
    Set d = New Dictionary
    d.Add "james", 1
    d.Add "william", 2
    d.Add "ravenswood", 3

    Close #1
    Open "C:\TestFolder\dict.txt" For Output As #1
    For Each i In d.Keys
        Print #1, i & d.Item(i)
    Next i
    Close #1
    Set d = Nothing
End Sub
查看更多
叼着烟拽天下
3楼-- · 2019-08-29 17:46

Assuming the keys and values in this dictionary are string, you could call a function like this and then use FileSystemObject or other method to create and write a textfile (example here).

Simply pass your dictionary object to the function in the FSO.WriteFile line like:

Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile("C:\desktop\textfile.txt") 'Modify as needed
oFile.Write PrintDictionary(twitter_dictionary)           'modify as needed
set fso = Nothing: set oFile = Nothing

Here is the function:

Function PrintDictionary(dict as Object) As String

Dim k as Variant
Dim i as Long
Dim fullText as String

For each k in dict.Keys()
    fullText = fullText & k & vbTab & dict(k) & vbCrLF
Next

PrintDictionary = fullText

End Function
查看更多
登录 后发表回答