简体   繁体   中英

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$1")).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

I am trying to make a pivot table with this code. The first try went well as it had no sheets. When I tried for the second time it gave me an error as the sheet already existed with table in it having the same name as the previous one.

The error is

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

When I delete the worksheet created in the previous step and try running the macro again works properly, but it does not works without deleting it.

you can try this at the top:

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

if it exists, it will be deleted and your code will make the new one. Does it help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM