在 VBA 中使用 Unicode 文件名(使用 Dir、FileSystemObject 等) [英] Working with Unicode file names in VBA (using Dir, FileSystemObject, etc.)
问题描述
我正在迭代文件夹中的文件(这意味着我不知道文件夹中的名称),并且有一个带有波兰语 ł
字符的文件.
I am iterating through files in a folder (which means I do not know the names in the folder), and have a file with a Polish ł
character.
Dir
函数将其转换为 l
,这意味着以后无法找到文件名.我已经声明了我将 dir 值指定为字符串的 var.
The Dir
function converts this to an l
which means the filename can't be found at a later date. I've declared the var that I'm assigning the dir value to as a string.
我也试过 FSO 和 getfolder,它们也有同样的问题.
I've also tried FSO and getfolder which also has the same issue.
我还注意到文件对话框(设置为文件夹选择模式)也转换了上面的字符.
I've also noticed the file dialog (set to folder select mode) converts the character above too.
这是一个错误,还是可以解决的问题?
Is this a bug, or is it something that can be worked around?
推荐答案
您似乎被以下事实误导了:虽然 VBA 本身支持 Unicode 字符,但 VBA 开发环境 没有.VBA 编辑器仍然使用基于 Windows 中区域设置的旧代码页"字符编码.
It sounds like you are being misled by the fact that while VBA itself supports Unicode characters, the VBA development environment does not. The VBA editor still uses the old "code page" character encodings based on the locale setting in Windows.
当然FileSystemObject
等.al. 实际上支持文件名中的 Unicode 字符,如以下示例所示.包含三个纯文本文件的文件夹
Certainly FileSystemObject
et. al. do in fact support Unicode characters in file names, as illustrated by the following example. With a folder containing three plain text files
文件名:1_English.txt
内容:伦敦是英格兰的一座城市.
文件名:2_French.txt
内容:巴黎是法国的一座城市.
文件名:3_Połish.txt
内容:华沙是波兰的一座城市.
以下VBA代码...
Option Compare Database
Option Explicit
Sub scanFiles()
Dim fso As New FileSystemObject, fldr As Folder, f As File
Set fldr = fso.GetFolder("C:\__tmpso33685990files")
For Each f In fldr.Files
Debug.Print f.Path
Next
Set f = Nothing
Set fldr = Nothing
Set fso = Nothing
End Sub
... 在立即窗口中产生以下输出...
... produces the following output in the Immediate window ...
C:\__tmpso33685990files1_English.txt
C:\__tmpso33685990files2_French.txt
C:\__tmpso33685990files3_Polish.txt
注意Debug.Print
语句将ł
字符转换为l
,因为VBA开发环境无法显示ł
代码> 使用我的 Windows 语言环境(美国英语).
Note that the Debug.Print
statement converts the ł
character to l
because the VBA development environment cannot display ł
using my Windows locale (US English).
但是,以下代码确实成功打开了所有三个文件...
However, the following code does open all three files successfully ...
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:\__tmpso33685990files")
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.
这篇关于在 VBA 中使用 Unicode 文件名(使用 Dir、FileSystemObject 等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!