在VBA中使用Unicode文件名(使用Dir,FileSystemObject等)

use*_*372 9 unicode ms-access vba dir ms-access-2013

我正在遍历文件夹中的文件(这意味着我不知道文件夹中的名称),并且有一个带有波兰?字符的文件.

Dir函数将其转换为a l,这意味着以后无法找到文件名.我已经声明了var,我将dir值指定为字符串.

我也尝试过FSO和getfolder也有同样的问题.

我还注意到文件对话框(设置为文件夹选择模式)也会转换上面的字符.


这是一个错误,还是可以解决的问题?

Gor*_*son 7

听起来您被VBA本身支持Unicode字符而VBA开发环境却不支持这一事实所迷惑。VBA编辑器仍然根据Windows中的区域设置使用旧的“代码页”字符编码。

当然FileSystemObject 等。等 实际上在文件名中支持Unicode字符,如以下示例所示。与包含三个纯文本文件的文件夹

文件名:1_English.txt
内容:London is a city in England.

文件名:2_French.txt
内容:Paris is a city in France.

文件名:3_Po?ish.txt
内容:Warsaw is a city in Poland.

以下VBA代码...

Option Compare Database
Option Explicit

Sub scanFiles()
    Dim fso As New FileSystemObject, fldr As Folder, f As File
    Set fldr = fso.GetFolder("C:\__tmp\so33685990\files")
    For Each f In fldr.Files
        Debug.Print f.Path
    Next
    Set f = Nothing
    Set fldr = Nothing
    Set fso = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)

...在立即窗口中产生以下输出...

C:\__tmp\so33685990\files\1_English.txt
C:\__tmp\so33685990\files\2_French.txt
C:\__tmp\so33685990\files\3_Polish.txt
Run Code Online (Sandbox Code Playgroud)

请注意,该Debug.Print语句将?字符转换为,l因为VBA开发环境无法?使用我的Windows语言环境(美国英语)显示。

但是,以下代码确实成功打开了所有三个文件...

Option Compare Database
Option Explicit

Sub scanFiles()
    Dim fso As New FileSystemObject, fldr As Folder, f As File, ts As TextStream
    Set fldr = fso.GetFolder("C:\__tmp\so33685990\files")
    For Each f In fldr.Files
        Set ts = fso.OpenTextFile(f.Path)
        Debug.Print ts.ReadAll
        ts.Close
        Set ts = Nothing
    Next
    Set f = Nothing
    Set fldr = Nothing
    Set fso = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)

...显示

London is a city in England.
Paris is a city in France.
Warsaw is a city in Poland.
Run Code Online (Sandbox Code Playgroud)