检查文件是否存在,VBA认为它存在,types不匹配

使用下面的代码,自从我尝试将它压缩到一个复杂的情况以来,VBA认为这些文件在那里是不存在的。 是因为我的声明吗? 以前我以这种方式订购(在复杂的情况下),它工作得很好。 当我重新排列文件位置的声明时,它仍然认为文件在那里。 然后我试着改变ElseIf部分来说'<>“”',并把它分成两个独立的IF,但结果相同。

编辑正确的最终结果

If CreateObject("Scripting.FileSystemObject").FileExists(filelocation1) Then filelocation1 = Environ("USERPROFILE") & "\Desktop" & "\" & Format(Date, "ddmmyyyy") & ".xls" filelocation2 = "\\afsaztempe1na1\site\AFS-AZ-Tempe\Shared\CERTIFICATION\ProdDumpTest" & "\" & Format(Date, "ddmmyyyy") & Application.UserName & ".xls" Set wbI = ThisWorkbook Set wsI = wbI.Sheets("Production") If wsI.Range("A2").value = "" Then Exit Sub Set wbO = Workbooks.Add Application.ScreenUpdating = False Application.DisplayAlerts = False With wbO Set wsO = wbO.Sheets("Sheet1") ActiveWorkbook.SaveAs Filename:=filelocation1, FileFormat:=56 wsI.Range("A1:C100").Copy wsO.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False ActiveWorkbook.Save ActiveWorkbook.Close End With With wsI wsI.Range("A2:C200").ClearContents End With FileCopy Source:=filelocation1, Destination:=filelocation2 Application.DisplayAlerts = True Application.ScreenUpdating = True Exit Sub End If filelocation1 = Environ("USERPROFILE") & "\Desktop" & "\" & Format(Date, "ddmmyyyy") & ".xls" filelocation2 = "\\afsaztempe1na1\site\AFS-AZ-Tempe\Shared\CERTIFICATION\ProdDumpTest" & "\" & Format(Date, "ddmmyyyy") & Application.UserName & ".xls" If filelocation1 <> "" Then Application.ScreenUpdating = False Application.DisplayAlerts = False Set wbI = ThisWorkbook Set wsI = wbI.Sheets("Production") With wbO Set wbO = Workbooks.Open(filelocation1) If wsI.Range("A2").value = "" Then Exit Sub Set wsO = wbO.Sheets("Sheet1") wsI.Range("a2:c100").Copy wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues ActiveWorkbook.Save ActiveWorkbook.Close End With With wb1 Set wb1 = Workbooks.Open(filelocation2) Set ws1 = wb1.Sheets("Sheet1") Application.ScreenUpdating = False Application.DisplayAlerts = False wsI.Range("a2:c100").Copy ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues ActiveWorkbook.Save ActiveWorkbook.Close End With With wsI wsI.Range("A2:C200").ClearContents End With Application.DisplayAlerts = True Application.ScreenUpdating = True 

万一

如果你想检查一个文件的存在,你可以这样做:

 If CreateObject("Scripting.FileSystemObject").FileExists(filelocation1) Then 

另外,要从一个给定的名字打开一个工作簿,你应该这样做:

 Set wbO = Workbooks.Add(filelocation1)