Hi
As you have probably gathered, I'm pretty clueless with VBA and am still
stuck. I have two pieces of code that do what I require, its just putting it
all together that has me stumped.
This piece of code queries a database and names the range based on the
contents of cell M2.
Sub Gen_SQL()
Dim strConn As String
Dim strSQL As Variant
Dim strQueryName As String
strConn = ActiveSheet.Range("M3")
strSQL = ActiveSheet.Range("L5:L23")
strQueryName = ActiveSheet.Range("M2")
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
The next piece of code deletes the range defined in M2
Sub delrange()
Dim strQueryName As String
strQueryName = ActiveSheet.Range("M2")
Application.Goto Reference:=strQueryName
Range(strQueryName).Clear
Selection.Delete shift:=xlUp
End Sub
What I'm trying to accomplish is the following;
[1] Test if the range exists.
[2] If it does exist it must delete the range calling Sub delrange and then
recreate the data range, calling Sub Gen_SQL
[3] If it does not exist it must just create the range calling Sub Gen_SQL
[4] I'm probably pushing my luck here, but here goes... In the Sub Gen_SQL,
I would like to declare the destination for the range as a variable, instead
of hard coding as A6. Can this be done?
Hope you can help - Many thanks, Grant