iT邦幫忙

0

(已解決)excel vba 將 txt 檔內容建立 dictionary

小斑 2017-10-19 16:50:4810007 瀏覽

按下按鈕,會讀取txt檔,並建立dictionary。

///
txt 內容如下
key1→hi
key2→hello
key3→how are u
///

(→是tab)
tab前為key,tab後為value

目前已可讀取txt檔案,以及另外建立dictionary,但並不是透過txt所建立的dictionary。

我希望能透過txt檔內容建立dictionary。

目前程式碼如下:

Private Sub Button_Click()

'   讀取.txt檔案
    Dim objStream As Object
    Set objStream = CreateObject("ADODB.Stream")

    With objStream
            .Type = 2
            .Mode = 3
            .Open
            .Charset = "UTF-8"
            .LoadFromFile ".txt檔案路徑"
             MsgBox .ReadText
            .Close
    End With
    
'   建立dictionary
    Dim Dict As Object
    Set Dict = CreateObject("Scripting.Dictionary")
    
    Dict.Add "key1", "hi"
    Dict.Add "key2", "hello"
    Dict.Add "key3", "how are u"
    MsgBox Dict("key2")
    
End Sub

/images/emoticon/emoticon41.gif

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
timloo
iT邦研究生 2 級 ‧ 2017-10-20 11:33:51
最佳解答

你的問題,網上也有人問過,google "excel vba read text file",
stackoverflow 有讀文字檔的sample code,

Dim FileNum As Integer
Dim DataLine As String

FileNum = FreeFile()
Open "Filename" For Input As #FileNum

While Not EOF(FileNum)
    Line Input #FileNum, DataLine ' read in data 1 line at a time
    ' decide what to do with dataline, 
    ' depending on what processing you need to do for each case
Wend

代碼中的DataLine ,應該是一line 一line的讀出。

接著你的需求是 切出欄位,你是用tab 做為分隔符號,
可google "excel vba split string tab" ,split 在java 是內建好用的函數,我用此做關鍵字,
可參考stackoverflow

Dim strCols As Variant
strCols = Split(strRows(0), vbTab)

大概是這段有切割的效果。strRows(0)換成DataLine

 Set cells = CreateObject("Scripting.Dictionary")
    For col = 0 To UBound(strCols) - 1
        cells.Add headers.Item(col + 1), strCols(col)
    Next

這段範例code ,和你的需求接近,你的strCols,應該是strCols(0)(key),strCols(1)(value)。 把切好的key,value,放入Dictionary。

以上供參考。

小斑 iT邦新手 3 級 ‧ 2017-10-24 19:59:47 檢舉

/images/emoticon/emoticon41.gif

我要發表回答

立即登入回答