Public Sub vEmployee_Update()
'strConnection = "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & ";Trusted_Connectionection=Yes"
'strConnection = "Provider=MSOLEDBSQL;Server=" & Server_Name & ";Database=" & Database_Name & ";Trusted_Connectionection=Yes"
'For Oracle
' With ActiveSheet.ListObjects.Add(SourceType:=0, Source:="OLEDB;Provider=OraOLEDB.Oracle;Data Source=myDB;OSAuthent=1;", _
' Destination:=Range("$A$1")).QueryTable
' End With
Dim ServerName As String, DatabaseName As String
Dim table As ListObject
Dim Connection As String, CommandText As String
Dim p1 As Long, p2 As Long
ServerName = Environ("COMPUTERNAME")
DatabaseName = "AdventureWorks2019"
With ThisWorkbook.Worksheets("vEmployee")
Set table = Nothing
On Error Resume Next
Set table = .ListObjects(1)
On Error GoTo 0
If table Is Nothing Then
Set table = .ListObjects.Add(SourceType:=0, _
Source:="OLEDB;Provider=MSOLEDBSQL; Server=" & ServerName & "; Database=" & DatabaseName & "; Trusted_Connection=Yes", _
Destination:=.Range("$A$1"))
With ThisWorkbook.Connections(1)
.Name = "vEmployee"
.Description = "Connection to vEmployee view"
End With
With table.QueryTable
.CommandText = "SELECT vEmployee.FirstName, vEmployee.LastName, vEmployee.JobTitle, vEmployee.EmailAddress FROM " & DatabaseName & ".HumanResources.vEmployee vEmployee"
.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_SQL_Server_" & DatabaseName
End With
Else
Connection = table.QueryTable.Connection
p1 = InStr(Connection, "Server=") + Len("Server=")
p2 = InStr(p1, Connection, ";")
Connection = Left(Connection, p1 - 1) & ServerName & Mid(Connection, p2)
p1 = InStr(Connection, "Workstation ID=") + Len("Workstation ID=")
p2 = InStr(p1, Connection, ";")
Connection = Left(Connection, p1 - 1) & ServerName & Mid(Connection, p2)
p1 = InStr(Connection, "Database=") + Len("Database=")
p2 = InStr(p1, Connection, ";")
Connection = Left(Connection, p1 - 1) & DatabaseName & Mid(Connection, p2)
table.QueryTable.Connection = Connection
CommandText = table.QueryTable.CommandText
p1 = InStr(CommandText, "FROM ") + Len("FROM ")
p2 = InStr(p1, CommandText, ".")
CommandText = Left(CommandText, p1 - 1) & DatabaseName & Mid(CommandText, p2)
table.QueryTable.CommandText = CommandText
table.QueryTable.ListObject.DisplayName = "Table_Query_from_SQL_Server_" & DatabaseName
End If
table.QueryTable.Refresh BackgroundQuery:=False
End With
End Sub