将VBA字典写入文本文件

时间:2014-04-25 13:30:49

标签: vba excel-vba excel

我将twitter搜索api结果存储为Excel VBA字典。我想把字典写成文本文件。我怎么做?

2 个答案:

答案 0 :(得分:3)

考虑:

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

答案 1 :(得分:3)

假设此字典中的键值是字符串,您可以调用这样的函数,然后使用FileSystemObject或其他方法来创建和编写文本文件(例如here)。

只需将字典对象传递给FSO.WriteFile行中的函数,如:

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

这是功能:

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