FileSystemObject创建含Unicode字符路径报错76的技术求助
问题排查与解决方法
针对FileSystemObject处理Unicode路径报错的问题,你可以从以下几个方向排查:
1. 确保路径字符串在VBA中保持Unicode格式
VBA的String虽然内部是Unicode,但从Excel单元格读取时,如果系统代码页不支持目标字符,会被转成替代字符。读取路径时改用Variant类型接收,或者用StrConv强制转成Unicode:
' 读取单元格路径的正确方式 Dim cellPath As Variant cellPath = Sheet1.Range("A1").Value ' 用Variant避免ANSI转换 ' 或者用StrConv显式转换 Dim rawPath As String, unicodePath As String rawPath = Sheet1.Range("A1").Value unicodePath = StrConv(rawPath, vbUnicode)
2. 替换Trim函数,避免Unicode处理异常
你代码里的Trim(Path)是基于ANSI的,对Unicode空格或特殊字符可能处理出错。改用FileSystemObject的路径处理方法,或者手动去空格:
' 替换Trim(Path)为 Path = FileSysObj.GetAbsolutePathName(Path) ' 或者手动处理首尾空格 Path = LTrim(RTrim(Path))
3. 直接调用Windows Unicode API替代FileSystemObject
如果FileSystemObject还是有兼容性问题,用CreateDirectoryW(Windows API的Unicode版本)直接创建目录,完全绕过VBA的字符串编码限制:
Private Declare PtrSafe Function CreateDirectoryW Lib "kernel32" (ByVal lpPathName As LongPtr, ByVal lpSecurityAttributes As LongPtr) As Boolean Private Declare PtrSafe Function GetLastError Lib "kernel32" () As Long Function MakeDir(Path As String) As Boolean Dim success As Boolean success = CreateDirectoryW(StrPtr(Path), 0) ' 处理目录已存在的情况(API返回False但错误码为183) If Not success Then Dim errCode As Long errCode = GetLastError() If errCode = 183 Then MakeDir = True Else Call ErrorHandle("MakeDir", errCode, "创建目录失败", "") MakeDir = False End If Else MakeDir = True End If End Function
这个方法不受系统区域设置影响,能完美处理任意Unicode路径。
4. 检查存储路径的Excel文件格式
如果用的是旧版.xls格式,它对Unicode字符支持有限,建议把存储路径的文件转成.xlsx格式,确保字符不会丢失或转码。
内容的提问来源于stack exchange,提问作者Cachalot
相关产品推荐
相关产品推荐

