使用下面的代码,自从我尝试将其压缩到复杂的if,VBA认为文件存在时就不存在了。是因为我的宣言吗?以前我以这种方式订购(在复杂的if之前)并且它工作正常。当我重新安排我对filelocations的声明时,它仍然认为该文件存在。然后我尝试更改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
结束如果
答案 0 :(得分:2)
如果要检查文件是否存在,可以这样做:
If CreateObject("Scripting.FileSystemObject").FileExists(filelocation1) Then
另外,要从给定名称打开工作簿,您应该这样做:
Set wbO = Workbooks.Add(filelocation1)