2014-05-10 42 views
3

文件我有VBA中寫入一個文本到.txt文件子程序:寫入在VBA長名稱爲Mac

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 For Output As #1上提出錯誤Bad file name or number

但我需要寫大量的文件,其名稱是長的...

其實,這個問題是很常見的。例如,this link也提到There are problems with long file names when you use Dir on a Mac, 27/28 characters (without the ext) is the maximum(with the extension this is 32 characters).

看來AppleScript可能是一個解決方案。但由於我正在尋找的解決方法,請寫而不是Dir,我還沒有找到寫入的精確解決方案。

有誰知道如何做到這一點?

回答

0

這是一個更早的,自從刪除的答案更健壯的版本。與使用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 
0

的不雅和不令人滿意的(但簡單)的替代方法是

  1. 輸出寫入保留文件名這足夠短到不會引起問題
  2. 寫入完成與文件後已關閉,請使用FileCopy將該短名稱文件複製到您實際需要的長名稱
  3. 刪除短名文件

事實證明,FileCopy是不是如此挑剔的文件名長度。

您可能希望將所有內容都包含在檢查中,以確保在編寫之前保留的名稱不存在,並確保在刪除具有保留名稱的文件時,如果發生任何類型的連結你有它開放。或者,您可以向用戶開放您正在做的事情,並在一開始就向用戶查詢這兩個名稱。 -HTH

0

我知道這是一個古老的線程,但...

作爲一種變通方法,使用短名稱創建該文件,然後使用VBA語句Name的文件重命名爲更長的名稱。這適用於Excel Mac 2011.

Open "Macintosh HD:Users:joe:Documents:SO-23587418.txt" For Output As #1 
    Print #1, "Hello world!" 
    Close #1 

    Name "Macintosh HD:Users:joe:Documents:SO-23587418.txt" As "Macintosh HD:Users:joe:Documents:SO-23587418-11111111112222222222333333333344444444445555555555.txt"