Excelmacros用于检查文件的存在

我对VBA没有任何的了解。 我有Excel文件,其中包含文件path,我想在该位置find文件的存在。

我尝试了以下,但需要比这更好的东西

Sub Test_File_Exist_With_Dir() Dim FilePath As String Dim TestStr As String FilePath = ActiveSheet.Range("A7").Value TestStr = "" On Error Resume Next TestStr = Dir(FilePath) On Error GoTo 0 If TestStr = "" Then ActiveSheet.Range("B7").Value = 0 Else ActiveSheet.Range("B7").Value = 1 End If End Sub 

预期产出

  File path Existence C:\Users\Desktop\Excel\Jan15.txt 1 C:\Users\Desktop\Excel\Feb15.txt 1 C:\Users\Desktop\Excel\Mar15.txt 1 C:\Users\Desktop\Excel\Apr15.txt 0 C:\Users\Desktop\Excel\May15.txt 0 

如果我将新行添加到数据,那么它的存在应该自动填充。

丘可以直接在工作簿中使用这个函数作为一个经典的Excel公式,只需键入=File_Exist(A1) ,这将作为一个正常的函数(你可以自动填充下一行很容易)。

 Public Function File_Exist(ByVal FilePath As String) As Integer On Error Resume Next Dim TestStr As String TestStr = Dir(FilePath) On Error GoTo 0 If TestStr <> "" Then File_Exist = 1 Else File_Exist = 0 End If End Function 

如果你想自动testing存在和填充每一次你添加新行到数据,那么你将不得不使用Worksheet_SelectionChange但它会比这更难,而不是如此有用,如果你有一个实用的function!