1

I have built a macro, wherein data is first imported into 'Raw' worksheet. Before importing, 'Raw' sheet is first cleared of previous data.
Then i query it using SQL in VBA and get the final output in desired format.
Lately i have been facing an issue, which gives a error message "The Connection for viewing your linked Microsoft Excel Worksheet was lost".

The same macro works fine if i dont clear the 'Raw' sheet before importing data. Any help is appreciated.

Option Explicit
Public ROW As Integer
Public Cnn As New ADODB.Connection
Public Rs As New ADODB.Recordset
Public StrSQL As String

Public Sub OpenDB()
    If Cnn.State = adStateOpen Then Cnn.Close
    Cnn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & _
    ActiveWorkbook.Path & Application.PathSeparator & ThisWorkbook.Name
    Cnn.Open
End Sub

Public Sub CloseRS()
    If Rs.State = adStateOpen Then Rs.Close
    Rs.CursorLocation = adUseClient
End Sub

Sub MonthlyYorN()



StrSQL1 = "SELECT * FROM [RAW$] where SOME CONDITION"
StrSQL1 = "SELECT * FROM [RAW$] where SOME CONDITION2"

StrSQL = StrSQL1 & " UNION " & StrSQL2

CloseRS
OpenDB

Rs.Open StrSQL, Cnn, adOpenKeyset, adLockOptimistic
If Rs.RecordCount > 0 Then
'Do Something
End If
End Sub
3
  • So much code to do something so simple - why not just use MS Query Commented Jan 16, 2015 at 12:33
  • @DaveSexton I have trimmed the Query while posting. The actual StrSQL1 and StrSQL2 are little complex query. Commented Jan 16, 2015 at 12:37
  • You can paste SQL statements directly into MS Query (or via VBA) so no matter how complex your statement that wouldn't be an issue.MS Query would handle all the data refreshing of the worksheet for you. Commented Jan 16, 2015 at 14:59

1 Answer 1

1

This is not a VBA issue, it's a problem with the ODBC Driver. Go to Windows KeyODBC to open Data Sources, then into the Advanced Settings for the Excel ODBC Driver, and make sure to turn on checkbox:

☑ Enable Automatic Reconnect

MS Access ODBC can experience the same problem, fixed the same way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.