2009年9月18日 星期五

匯入資料

今天耗在excel home好長的時間
記得之前寫過匯入資料的程式
在論壇中還是有很多人問類似的問題
本來想試著幫忙寫寫看
結果版主板友回得很快
而且程式碼又簡潔又迅速
相對的我寫的就差多了
Sub DAORU()
Dim s() As String, f As String, i As Long, b() As Byte
f = Dir(ThisWorkbook.Path & "\*.TXT")
While f > ""
Open ThisWorkbook.Path & "\" & f For Input As #1
s = Split(StrConv(InputB(LOF(1), 1), vbUnicode), vbCrLf)
Close #1
[a1].Offset(, i).Resize(UBound(s) + 1) = WorksheetFunction.Transpose(s)
i = i + 1
f = Dir()
Wend
MsgBox "OK"
End Sub
上面這個副程式 可以將所在資料夾內的文件檔分別輸出在各列
Sub m()
Dim f As String, s() As String, i As Long, j As Long, arr(10000, 255)
f = Dir(ThisWorkbook.Path & "\*.txt")
While f > ""
Open ThisWorkbook.Path & "\" & f For Input As #1
s = Split(StrConv(InputB(LOF(1), 1), vbUnicode), vbCrLf)
Close #1
arr(0, j) = Split(f, ".")(0)
For i = 0 To UBound(s)
arr(i + 1, j) = Split(s(i), vbTab)(0)
arr(i + 1, j + 1) = Split(s(i), vbTab)(1)
Next
j = j + 2
f = Dir
Wend
[a1].Resize(10001, j + 2) = arr
End Sub
另外這個是進階版 每個文件內每行有兩筆資料
不但在第一行輸出檔案名稱 也成功的把每筆資料對應的輸出到儲存格
從這次看到的程式碼裡
我學到除了用input,line input加上迴圈來處理讀檔外
其實有更快的方式讀檔
從網路上找到以下的讀檔方式
這次使用的程式也是用這種方法
--------------------------------------------------------------------------------

使用 TextBox 顯示文字檔內容,通常對應設計的程式片段是
 

txtContent.Text = "" '清除內容

Open sFile$ For Input As #1 '開啟文字檔

While Not EOF(1) '未到檔案尾端

Line Input #1, a$ '逐行讀取

txtContent.Text = txtContent.Text & a$ & vbCrLf '逐行加入txtContent及換行符號

Wend '反覆執行

Close #1 '關閉檔案


若是將 TextBox(txtContent) 顯示內容 的處理敘述略作變更,將可加快處理速度

 

txtContent.Text = "" '清除內容

Open sFile$ For Input As #1 '開啟文字檔

While Not EOF(1) '未到檔案尾端

Line Input #1, a$ '逐行讀取

txtContent.SelText = a$ & vbCrLf '逐行加入txtContent及換行符號

Wend '反覆執行

Close #1 '關閉檔案


其中的道理是:
因為 txtContent.Text = txtContent.Text & a$ & vbCrLf 會安排一個記憶體位置儲存等式右側的運算結果,再清除 txtContent 原有內容,以此一運算結果取代之,其間包含許多的動作;而 txtContent.SelText = a$ & vbCrLf 是直接把右側的運算結果放入 txtContent 裡,少了很多不必要的的動作,所以比較快。

此外,以單一敘述一次讀入整個檔案更可加快完成

 

txtContent.Text = "" '清除內容

Open sFile$ For Input As #1 '開啟文字檔

txtContent.Text = StrConv(InputB(LOF(F), #1), vbUnicode) '一次讀入整個檔案

Close #1 '關閉檔案

沒有留言:

張貼留言