使用 VBA 替换 excel 2007 中现有的 sheet

Replacing the existing sheet in excel 2007 using VBA

Sub testmac()
'
' testmac Macro
'
'
    ActiveWorkbook.Names.Add Name:="items", RefersToR1C1:= _
        "=Report!R7C8:R486C11"
    ActiveWorkbook.Worksheets.Add
    With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
        "ODBC;DSN=Excel Files;DBQ=path
        ), Array("P;DriverId=1046;MaxBufferSize=2048;PageTimeout=5;")), Destination:= _
        Range("$A")).QueryTable
        .CommandText = Array( _
        "TRANSFORM first(`Dimension Value Code`)" & Chr(13) & "" & Chr(10) & "SELECT items.`No#`, items.`Description`" & Chr(13) & "" & Chr(10) & "FROM items" & Chr(13) & "" & Chr(10) & "GROUP BY items.`No#`, items.`Description`" & Chr(13) & "" & Chr(10) & "PIVOT `Dimension Code`" _
        )
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "Table_Query_from_Excel_FilesXY"
        .Refresh BackgroundQuery:=False

        End With

End Sub

我正在尝试使用此代码创建一个枢轴 table。第一次尝试很顺利,因为它没有 sheets。当我第二次尝试时,它给了我一个错误,因为 sheet 已经存在,其中 table 与前一个同名。

错误是

Run-time error '1004': Application-defined or object defined error

当我删除在上一步中创建的作品sheet 并尝试运行 宏再次正常工作,但不删除它就无法工作。

你可以在顶部试试这个:

on error resume next
ActiveWorkbook.Sheets("your sheet").delete
on error goto 0

如果存在,它将被删除,您的代码将生成新的。有帮助吗?