删除并创建具有相同名称的新工作簿

时间:2018-01-19 10:18:23

标签: excel vba excel-vba excel-2010

我想创建一个名为' Land-DE'的新工作簿。如果该文件已存在于目录中,则必须在创建新文件之前自动将其删除。我尝试过使用以下代码,但它无效。

Sub createwb()
    Workbooks.add
    Dim FSO
    Dim path As String
    Set FSO = CreateObject("Scripting.FileSystemObject")
    set path = "D:\Job\Land-DE.xlsx"
    If FSO.FileExists(path) Then
        FSO.DeleteFile path, True
    else
        ActiveWorkbook.SaveAs "D:\Job\Land-DE.xlsX"
    End If
End Sub

4 个答案:

答案 0 :(得分:4)

为什么必须在保存之前将其删除?这还不够:

Application.DisplayAlerts = False
ActiveWorkbook.SaveAs "D:\Job\Land-DE.xlsx"
Application.DisplayAlerts = True

答案 1 :(得分:3)

看看以下内容。这将检查是否存在path中定义了名称的文件,如果是,请在再次保存之前将其删除。

Sub Createwb()
    Dim path As String

    path = "D:\Job\Land-DE.xlsx"

    If Dir(path) <> "" Then Kill path

    ActiveWorkbook.SaveAs path
End Sub

答案 2 :(得分:1)

Sub createwb()
    Workbooks.Add
    Dim FSO
    Dim path As String
    Set FSO = CreateObject("Scripting.FileSystemObject")
    path = "D:\Job\Land-DE.xlsx"
    If FSO.FileExists(path) Then
        FSO.DeleteFile path, True
    End If
    ActiveWorkbook.SaveAs path
End Sub

两件事:Set用于设置对象。那里的路径只是一个字符串变量。对象是一组函数和变量,就像您在其上面创建的FSO对象一样。

接下来,您需要确保在删除它之后保存,并且当您再次循环时,保存的最后一个版本仍未打开。如果是,您将被拒绝尝试保存当前打开的文件。

答案 3 :(得分:1)

您的代码存在多个问题

set path = "D:\Job\Land-DE.xlsx" 'It is syntax error, you can only set object in VBA , string is not considered as object

FSO.DeleteFile path, True 'USE kill instead, better performance
ActiveWorkbook.SaveAs "D:\Job\Land-DE.xlsX" ' Do not user active keyword, always set the object

以下是代码:

Sub createwb()

    Dim wbnew As Workbook
    Set wbnew = Workbooks.Add

    Dim path As String
    path = "D:\Job\Land-DE.xlsx"

    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
            If FSO.FileExists(path) Then
            On Error Resume Next
                Workbooks("Land-DE").Close False ' Close the workbook if open
            Kill path
            wbnew.SaveAs path
    Else
        wbnew.SaveAs path
    End If
End Sub