我有一个子例程,它在 VBA 中将文本写入 .txt
文件:
Sub WriteToFile(fileName as String, content as String)
Open fileName For Output As #1
Print #1, content
Close #1
End Sub
这个子程序在 Windows 下运行良好。但是,我意识到在 Mac 下,对于任何超过 29 个字符的 targeFile
,将在 Open fileName 行引发错误
。Bad file name or number
对于输出为 #1
但是我确实需要写入很多名称很长的文件...
其实这个问题很常见。例如,this link还提到 在 Mac 上使用 Dir 时存在长文件名问题,最大 27/28 个字符(不带扩展名)(扩展名是 32 个字符)。
看来 AppleScript
可能是解决这个问题的方法。但由于我正在寻找writing 而不是Dir
的解决方法,因此我还没有找到writing 的精确解决方案。
有人知道如何实现吗?
最佳答案
这是较早的已删除答案的更强大版本。与使用 do shell script
的已删除答案不同,此答案仅使用 AppleScript 命令字符串中的 AppleScript 功能,并且还正确地转义了嵌入命令字符串中的参数。
尝试以下 VBA 过程,它合成一个 AppleScript 命令字符串以写入文件并使用 MacScript
执行它。
' - Specify the output filename either as a mere filename -
' in which case the file is created in the active workbook's folder -
' or as a HFS path (with ':' as the path separator).
' - Note that line breaks in `content` are written as defined,
' and that on a Mac `vbNewLine` is chr(13) (CR == \r) only.
' If you want Unix-style LF (\n) line breaks instead, use chr(10) explicitly.
' Example:
' WriteToFile "test.txt", "Hello, world." & Chr(10)
Sub WriteToFile(fileName As String, content As String)
Dim filePath, filePathEscaped, contentEscaped, asCmd
' If the filename contains no path component, default to the active workbook's path.
If InStr(fileName, ":") = 0 Then
filePath = ActiveWorkbook.Path & ":" & fileName
Else
filePath = fileName
End If
' In case the file path or input string contain double quotes, we must
' \-escape them for inclusing in the AppleScript command string first.
filePathEscaped = Replace(filePath, """", "\""")
contentEscaped = Replace(content, """", "\""")
' Synthesize the AppleScript command string.
asCmd = _
"set fRef to open for access """ & filePathEscaped & _
""" with write permission" & Chr(13) & _
"set eof fRef to 0" & Chr(13) & _
"write """ & contentEscaped & """ to fRef" & Chr(13) & _
"close access fRef"
' Execute the AppleScript command string.
' Any error will generically be reported as "Invalid procedure call or
' argument", unfortunately.
MacScript asCmd
End Sub
关于excel - 在 VBA for Mac 中写入具有长名称的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23587418/