Option Explicit
Sub Import_Dati()
Dim sPath As String, sFile As String, sQuery As String
Dim sCampo1 As String, sCampo2 As String
Dim rDest As Range
Dim lMax As Long, lMin As Long
Dim ws As Worksheet
sPath = "C:Prove" 'dove pescare il file
sFile = "Data base.xlsm" 'quale file pescare
Set ws = ThisWorkbook.Worksheets("Query - tab1") 'in che foglio importare i dati
On Error Resume Next
ws.ListObjects("Dati_Importati").Delete
On Error GoTo 0
Set rDest = ws.Range("I2") 'dove importare i dati
'''MACRO IMPOSTATA SU DUE SOLI CAMPI, VOLENDO MODIFICABILE CON UN CICLO IF PER CONTROLLARE QUANTI CAMPI SONO STATI INSERITI
sCampo1 = ws.Range("B2")
sCampo2 = ws.Range("B3")
lMin = ws.Range("C3")
lMax = ws.Range("D3")
'stringa SQL per la query
sQuery = "SELECT `'Tabella 1$'`." & sCampo1 & ",`'Tabella 1$'`." & sCampo2 & Chr(13) & _
"FROM `'Tabella 1$'` `'Tabella 1$'`" & Chr(13) & _
"WHERE (`'Tabella 1$'`." & sCampo2 & ">" & lMin & "And `'Tabella 1$'`." & sCampo2 & "<=" & lMax & ")" & Chr(13) & _
"ORDER BY `'Tabella 1$'`.età DESC"
With ws.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=Excel Files;DBQ=" & sPath & "" & sFile & ";DefaultDir=" & sPath & ";DriverId=1046;MaxBufferSize=2048;PageTimeout=5;" _
, Destination:=rDest).QueryTable
.CommandText = sQuery
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Dati_Importati"
.Refresh BackgroundQuery:=False
End With
Set rDest = Nothing
Set ws = Nothing
End Sub |