【发布时间】:2022-08-17 16:49:39
【问题描述】:
我正在尝试检查文件夹中是否存在特定文件。
例如在我的代码中,文件夹 1 有 3 个文件,文件夹 2 有 1 个文件。
我希望输出让我知道文件“存在”或“不存在”
有一个错误。 filename3 = ActiveSheet.Range(\"B21\").Value 不存在,但消息框显示它存在。我认为这与我加入文件路径+文件名的方式有关。
另外,有什么方法可以让代码更优雅?
Sub InputChecker()
Dim filepath As String
Dim filename As String
Dim result1 As String
Dim fullpath As String
filepath1 = ActiveSheet.Range(\"H14\").Value
filename1 = ActiveSheet.Range(\"H15\").Value
filename2 = ActiveSheet.Range(\"H16\").Value
filename3 = ActiveSheet.Range(\"B21\").Value
filepath2 = ActiveSheet.Range(\"H18\").Value
filename4 = ActiveSheet.Range(\"H19\").Value
Dim fullpath1 As String
fullpath1 = filepath1 & filename1
If Dir(fullpath1) = VBA.Constants.vbNullString Then
result1 = filename1 + \", File does not exist\"
Else
result1 = filename1 + \", File exist\"
End If
Dim fullpath2 As String
fullpath2 = filepath1 & filename2
If fullpath2 = VBA.Constants.vbNullString Then
result2 = filename2 + \", File does not exist\"
Else
result2 = filename2 + \", File exist\"
End If
Dim fullpath3 As String
fullpath3 = filepath1 & filename3
If fullpath3 = VBA.Constants.vbNullString Then
result3 = filename3 + \", File does not exist\"
Else
result3 = filename3 + \", File exist\"
End If
Dim fullpath4 As String
fullpath4 = filepath2 & filename4
If fullpath4 = VBA.Constants.vbNullString Then
result4 = filename4 + \", File does not exist\"
Else
result4 = filename4 + \", File exist\"
End If
MsgBox (result1 & vbNewLine & result2 & vbNewLine & result3 & vbNewLine & result4)
Cells(18, 3).Value = Format(Now, \"yyyy-MM-dd hh:mm:ss\")
End Sub
-
你已经得到了
If Dir(Fullpath1),这是正确的,你需要在完整路径 2、3 和 4 的其他测试中使用Dir命令 -
哦,哇,我完全错过了那个简单的部分,谢谢指出。它现在工作正常。现在看起来就像非常笨拙的编码。