2012-07-31 82 views
2

在Excel-VBA時,我使用下面的代碼保存文件:如何挽救回來的消息框點擊「否」來替換文件

fullFileName = Application.GetSaveAsFilename(...) 
ActiveWorkbook.SaveAs fullFileName 

這工作得很好,直到已經選擇的名稱存在。消息框然後提示:「文件是否應該被替換?」。我想回答No,並返回到上一個消息框並選擇另一個名稱。

而是,單擊No會中斷宏併產生錯誤。

我該如何解決這個問題?

(該網站是充滿了示例來說明如何使用Application.DisplayAlerts=False繞過此消息框,並保存反正這不是我想要的!)

回答

3

這通常是我用什麼...

Sub Sample() 
    Dim fullFileName 

    fullFileName = Application.GetSaveAsFilename(_ 
        fileFilter:="Text Files (*.txt), *.txt") 
    If fullFileName <> False Then 
     If fileExists(fullFileName) = False Then 
      ActiveWorkbook.SaveAs fullFileName 
     Else 
      MsgBox "File Exists. File Save Aborted" 
     End If 
    End If 
End Sub 

Public Function fileExists(strFullPath As Variant) As Boolean 
    On Error GoTo Whoa 
    If Not Dir(strFullPath, vbDirectory) = vbNullString Then fileExists = True 
Whoa: 
    On Error GoTo 0 
End Function 

FOLLOWUP

你的意思是這樣嗎?

Sub Sample() 
    Dim fullFileName 
    Dim conti As Boolean 

    conti = True 

    Do While conti = True 
     fullFileName = Application.GetSaveAsFilename(_ 
         fileFilter:="Text Files (*.txt), *.txt") 
     If fullFileName <> False Then 
      If fileExists(fullFileName) = False Then 
       ActiveWorkbook.SaveAs fullFileName 
       conti = False 
      Else 
       MsgBox "File Exists. Returning you back to the dialog box" 
      End If 
     Else 
      conti = False 
     End If 
    Loop 
End Sub 

Public Function fileExists(strFullPath As Variant) As Boolean 
    On Error GoTo Whoa 
    If Not Dir(strFullPath, vbDirectory) = vbNullString Then fileExists = True 
Whoa: 
    On Error GoTo 0 
End Function 
+0

謝謝悉達。用你的代碼,當文件存在時,保存被中止。有沒有辦法點擊「不,我不想替換現有的文件」並返回到「GetSaveAsFilename」對話框? – Nicolas 2012-07-31 14:27:32

+0

參見上面的跟進。 – 2012-07-31 14:37:19

+0

這是不可能的。感謝您的快速回復! – Nicolas 2012-08-01 08:05:01