如何杀死工作簿

时间:2019-05-12 19:20:25

标签: excel vba

下面的VBA代码应该执行以下操作: 如果存在具有SavedSourcePath名称的工作簿文件,则将其打开,然后关闭然后取消显示。 它可以正确打开它,但不要关闭它,但会收到错误消息“索引不在(?)列表中(法语为tableau)

请注意,一开始我不知道文件是否存在以及是否打开或关闭。我想在任何情况下都消失不见。

SavedSourcePath = "/Users/Shared/TS1/optim.xlsm"••••ˇˇˇˇ

If Dir(SavedSourcePath) <> "" Then
    Workbooks.Open (SavedSourcePath)
    Workbooks(SavedSourcePath).Close saveChanges:=False
    Kill Workbooks(SavedSourcePath)
End If

或者,有没有一种方法可以保存一个名称可能存在的工作簿,如果存在则将其崩溃?机智的人必须回答“你想……”

1 个答案:

答案 0 :(得分:-2)

这可能有帮助:

Sub openFile()

'First make sure the files are closed
On Error Resume Next
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
xlApp.DisplayAlerts = False
Call xlApp.Workbooks("originalFile.txt").Close
Call xlApp.Workbooks("newFile.csv").Close
Set xlApp = Nothing

'Delete the final file if it exist 
'the file can have the same name just need to be stored in different location
'or you will overwrite the existing file
Dim aFile As String
aFile = "C:\newlocation\newFile.csv"    
If Len(Dir$(aFile)) > 0 Then
     Kill aFile
End If

'Open the originalFile, run the code and save it to the desired location
'and give it a new filename and type
'if the file is not there, the program just ends
If Len(Dir("C:mydata\originalFile.txt")) > 0 Then

    Do Something

    ActiveWorkbook.SaveAs Filename:="C:\newlocation\newFile.csv", FileFormat:=xlCSV, _
    CreateBackup:=False
    Application.DisplayAlerts = False
    ActiveWorkbook.Close
    Application.DisplayAlerts = True

End If

End Sub