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

问题描述 投票:0回答:1

我正在迭代文件夹中的文件(这意味着我不知道文件夹中的名称),并且有一个带有波兰语

ł
字符的文件。

Dir
函数将其转换为
l
,这意味着以后无法找到文件名。我已经将要将 dir 值分配给的 var 声明为字符串。

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

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


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

vba ms-access unicode ms-access-2013 dir
1个回答
8
投票

听起来您被以下事实误导了:虽然 VBA 本身 支持 Unicode 字符,但 VBA 开发环境 不支持。 VBA 编辑器仍然使用基于 Windows 区域设置的旧“代码页”字符编码。

当然

FileSystemObject
等。 al. 实际上支持文件名中的 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

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

C:\__tmp\so33685990\files\1_English.txt
C:\__tmp\so33685990\files\2_French.txt
C:\__tmp\so33685990\files\3_Polish.txt

请注意,

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

...显示

London is a city in England.
Paris is a city in France.
Warsaw is a city in Poland.
© www.soinside.com 2019 - 2024. All rights reserved.