DEV Community

codemee
codemee

Posted on

1

在 VBA 中讀取 UTF8 編碼的文字檔

在 VBA 中, 如果要讀取文字檔, 可以使用 FileSystemObject 物件, 像是這樣:

Set file = CreateObject("Scripting.FileSystemObject").OpenTextFile(txname, 1)
Selection.Text = file.ReadAll
Enter fullscreen mode Exit fullscreen mode

其中 OpenTextFile 有第 3 個參數 create 可以指定當檔案不存在時是否要建立新檔案。另外還有第 4 個參數 format 可以指定檔案的編碼:

常數名稱 說明
TristateUseDefault -2 使用系統預設編碼開啟檔案
TristateTrue -1 以 Unicode 編碼開啟檔案
TristateFalse 0 以 ASCII 編碼開檔

不過要注意的是,上表中的 Unicode 指的是 UTF16 編碼, 並不能讀取 UTF8 編碼的文字檔案。

改用 ADODB.Stream 物件讀取 UTF8 編碼的文字檔

FileSystemObject 並不能隨意指定文字檔案的編碼, 如果需要讀取特定編碼格式的文字檔案, 就要改用 ADODB.Stream 物件, 像是這樣:

Set objStream = CreateObject("ADODB.Stream")

objStream.Charset = "utf-8"
objStream.Open
objStream.LoadFromFile (txname)

Selection.Text = objStream.ReadText()
Enter fullscreen mode Exit fullscreen mode

只要設定 Chaset 屬性, 就可以指定文字串流要採用的編碼格式, 即可透過 LoadFromFile 載入文字檔, 並可透過 ReadText 方法讀取文字檔案內容。

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More