Metod jest kilka ja podaje tylko 1 z nich
Sub zapytanie_SQL()
Dim Zapytanie As String
Dim Tabela As Worksheet
Set Tabela = Application.Workbooks("Plik.xls").Worksheets("tabela")
Tabela.Cells.ClearContents
Zapytanie = " SELECT * from BAZA.dbo.tabela Tabela "
Zapytanie = Zapytanie & " where Tabela.Kolumna=1 "
Zapytanie = Zapytanie & " ORDER BY Tabela.Kolumna "
With Tabela.QueryTables.Add(Connection:= _
"ODBC;DRIVER=SQL Server;SERVER=NAZWA_SERWERA;UID=LOGIN;PWD=HASŁO" _
, Destination:=Range("A1"))
.CommandText = Zapytanie
.PreserveFormatting = True
.BackgroundQuery = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh
End With
End Sub
Musisz tylko zmodyfikować zapytanie SQL pod swoje potrzeby oraz ustawić nazwę serwera login i hasło. Jeśli chcesz żeby pytał o hasło wycinasz fragment PWD=HASŁO |