2016-10-12 34 views
0

我想在運行我的代碼之前檢查文件是否已經存在。如果它存在比退出,否則保持我的代碼運行。我寫的是下面的代碼:我如何檢查文件是否存在使用Powerpoint中的VBA宏

Private Sub CommandButton21_Click() 

If FileFolderExists("C:\Users\Moez\Desktop\Macro_Project\Test1.pptm") Then 
    MsgBox "Modification already done!" 
Else 
    deleteTextBox 
    AllBlackAndDate 
    LastModifiedDate 
    SaveAllPresentations "C:\Users\Moez\Desktop\Macro_Project\Test1.pptm" ' save here 
End If 

End Sub   
+0

的可能的複製[檢查文件是否存在使用VBA(http://stackoverflow.com/questions/11573914/check-if-the-file-exists-using-vba) – vacip

+3

嘗試谷歌下一次。這已經在這裏被提出了一百次 - 這只是今年。 :) [1](http://stackoverflow.com/questions/16351249/vba-check-if-file-exists)[2](http://stackoverflow.com/questions/26551757/how-doi-i- check-if-a-file-exists-before-i-open-it-via-excel-vba)[3](http://stackoverflow.com/questions/4082539/how-do-i-determine-if- file-exists-vba-excel-2007)[4](http://stackoverflow.com/questions/35712855/test-if-file-exists-using-vba-or-excel-without-dir) – vacip

+1

' CommandButton21' ...考慮*命名*的東西。 ''TimestampAndSaveButton'(或其他)將在六個月後從'CommandButton42'中更容易分辨出來。 –

回答

4

如果您想檢查文件是否存在,你想用一個FileSystemObject在本地機器上。

Dim fso : Set fso = CreateObject("Scripting.FileSystemObject") 

if fso.FileExists("Your file name and path here") Then 
    ' do what you like in the case where the file exists 
Else 
    ' do whatever you wanted to do where the file doesn't exist 
End If 

讓我知道你是否需要任何進一步的解釋。

+1

不錯。我將添加到我的VBA庫。 – rohrl77

+1

Upvoted。 'FileSystemObject'對其他函數也非常有用。瞭解它會有所幫助。 :) –

+1

接下來可以寫成IF IF CreateObject(「Scripting.FileSystemObject」)。FileExists(「C:\ Users \ Moez \ Desktop \ Macro_Project \ Test1.pptm」)THEN'(最好用於一行函數返回TRUE/FALSE)。 –

2

這是我見過的最好的方式:

Sub test() 

thesentence = InputBox("Type the filename with full extension", "Raw Data File") 

If Dir(thesentence) <> "" Then 
    MsgBox "File exists." 
Else 
    MsgBox "File doesn't exist." 
End If 

End Sub 

信用這裏:

Check if the file exists using VBA

+0

與我的方法相同:-) – rohrl77

+0

這實際上是在Powerpoint中,而不是在Excel中。我嘗試過但它不起作用! – Zigouma

+0

@Zigouma立即試用 – User632716

1

這是我的東西,如果存在檢查的版本。包括一個測試子。這應該可以在包括PowerPoint在內的任何VBA環境中使用。

Sub test() 
MsgBox (FileFolderExists("C:\Users\Moez\Desktop\Macro_Project\Test1.pptm")) 
End Sub 

Private Function FileFolderExists(str As String) As Boolean 
Dim sCheck As String 
sCheck = Dir(str) 

If Len(sCheck) > 0 Then 
    FileFolderExists = True 
Else 
    FileFolderExists = False 
End If 
End Function 
相關問題