Mac端Office枚举含Unicode文件名的图片并插入的问题
Mac Office VBA 处理含Unicode文件名的图片插入方案
在Mac版MS Office中,Dir()函数无法识别含Unicode字符的文件名,且无法使用FileSystemObject库,要实现枚举文件夹图片并插入的需求,可以通过调用AppleScript绕过限制——Mac的Finder能正确处理Unicode路径和文件名,结合VBA的MacScript函数就能实现目标。
解决代码
Sub InsertUnicodeImages() Dim folderPath As String Dim appleScriptCode As String Dim fileNames As Variant Dim i As Integer Dim fullPath As String ' 替换为你的目标文件夹绝对路径(Mac格式:/Users/xxx/xxx) folderPath = "/Users/你的用户名/Desktop/图片文件夹" ' AppleScript代码:获取文件夹下所有jpg、png格式的文件名 appleScriptCode = "tell application ""Finder"" to get name of every file in folder """ & folderPath & """ whose name ends with ""jpg"" or name ends with ""png""" ' 执行AppleScript,返回文件名数组 fileNames = MacScript(appleScriptCode) ' 无文件时提示 If IsEmpty(fileNames) Then MsgBox "未找到图片文件", vbInformation Exit Sub End If ' 循环插入图片到Sheet1(默认每行插入一张,位置可自行调整) With ActiveWorkbook.Worksheets("Sheet1") For i = LBound(fileNames) To UBound(fileNames) fullPath = folderPath & "/" & fileNames(i) .Shapes.AddPicture _ Filename:=fullPath, _ LinkToFile:=msoFalse, _ SaveWithDocument:=msoTrue, _ Left:=.Cells(i + 1, 1).Left, _ Top:=.Cells(i + 1, 1).Top, _ Width:=100, _ Height:=100 Next i End With End Sub
关键说明
- 路径格式:必须使用Mac系统的绝对路径(以
/开头),不要用Windows风格的反斜杠 - 格式扩展:如果需要支持更多图片格式,在AppleScript代码里添加
or name ends with ""gif""这类条件即可 - 插入控制:
Shapes.AddPicture可以自定义图片的位置、宽高,比原代码的Pictures.Insert更灵活,避免手动选择操作
内容的提问来源于stack exchange,提问作者abdullah
相关产品推荐
相关产品推荐

