I am having trouble with this VBA script and it seems to keep adding funny characters (i.e.) every time it reads the .SQL file. I believe this is due to encoding.
Option Explicit
Sub SomeExtract()
With Application
.ScreenUpdating = False: .DisplayAlerts = False: .Calculation = xlCalculationManual: .EnableEvents = False
End With
Dim strSQL As String, filePath As String, fileSQL As Integer, row As String
Dim connSQL As ADODB.Connection, serverName As String, databaseName As String, userID As String, userPassword As String, rs As ADODB.Recordset
fileSQL = FreeFile
strSQL = ""
filePath = Application.ThisWorkbook.Path & "\somesql.sql"
Open filePath For Input As fileSQL
Do Until EOF(fileSQL)
Line Input #fileSQL, row
strSQL = strSQL & row & vbNewLine
Loop
Close #fileSQL
serverName = "someserver"
databaseName = "somedb"
Set connSQL = New ADODB.Connection
Set rs = New ADODB.Recordset
connSQL.Open "Provider=SQLOLEDB;Server=" & serverName & ";Database=" & databaseName & _
";Trusted_connection=yes;"
rs.Open strSQL, connSQL, adOpenStatic
With ThisWorkbook.Sheets("test").Range("A1:Z1000000")
.ClearContents
.CopyFromRecordset rs
End With
With Application
.ScreenUpdating = True: .DisplayAlerts = True: .Calculation = xlCalculationAutomatic: .EnableEvents = True
End With
ExitPoint:
With Application
.ScreenUpdating = True: .DisplayAlerts = True: .Calculation =
xlCalculationAutomatic: .EnableEvents = True
End With
Set rs = Nothing
Exit Sub
ErrHandler:
With ThisWorkbook
.Sheets("Control").Range("B1").Value = Err.Description
.Sheets("Control").Range("C1").Value = strSQL
End With
Resume ExitPoint
End Sub
The error message says "Run-time error '-2147217900 (80040e14)': Incorrect syntax near '>>';". The SQL file doesn't have >> or any other characters as shown on the error message. In fact, I have replaced the .sql to only contain a straight SELECT statement. But I still seeing the funny characters being added when it is being read by Excel VBA (e.g. select top 100 * from test" instead of "select top 100 * from test").