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

问题描述 投票:1回答:4

我想创建一个名为'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
excel vba excel-vba excel-2010
4个回答
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

4
投票

为什么必须在保存之前将其删除?这样就够了:

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

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对象一样。

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


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
© www.soinside.com 2019 - 2024. All rights reserved.