View Single Post
  #10   Report Post  
Posted to microsoft.public.excel.programming
Grant Reid Grant Reid is offline
external usenet poster
 
Posts: 51
Default Programatically deleting Range

Hi

Thanks to all who have responded. I've pretty much got the answer I needed
and scripted my code accordingly. There's only one problem....... After
running the code repeatedly, clicking on the Insert - Name - Define Menu
reveals defined names "Server1_Detail_1", "Server1_Detail_2",
"Server1_Detail_3" etc etc all with the similar invalid references ie
=Sheet2!#REF!.

Can anyone enlighten me how to remove these defined names and their invalid
references within the routine "DeleteAllQueries". The value in "D2"
determines the QueryTable name to be deleted and must also be used to delete
these invalid defined names.

Sub DeleteAllQueries()
Dim qt As QueryTable
Dim WSh As Worksheet
Dim strQueryName

For Each WSh In ThisWorkbook.Worksheets
strQueryName = WSh.Range("D2")
For Each qt In WSh.QueryTables
If InStr(qt.Name, strQueryName) Then
qt.ResultRange.ClearContents
qt.ResultRange.Delete
qt.Delete
End If
Next qt
Next WSh

End Sub

And for completeness, here is the code I use to generate the QueryTables;

Sub Gen_SQL()
Dim strConn As String
Dim strSQL As Variant
Dim strQueryName As String

strConn = ActiveSheet.Range("D3").Value
strSQL = ActiveSheet.Range("D5").Value
strQueryName = ActiveSheet.Range("D2").Value

With ActiveSheet.QueryTables.Add(Connection:=strConn,
Destination:=Range("A6"), Sql:=strSQL)
.Name = strQueryName
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = True
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = False
.RefreshStyle = xlOverwriteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.PreserveColumnInfo = False
.Refresh BackgroundQuery:=False
End With
End Sub

Many Thanks - Grant