Much ADO about text files

beedistinct

Board Regular
Joined
Jun 24, 2011
Messages
62
Am at my wits' end. what is wrong with the code below? It is giving me an error
"ADODB Connection --> Operation is not allowed when the object is closed."
Code:
Public Sub GetTextFileData()
 Dim cn As ADODB.Connection, rs As ADODB.Recordset, f As Integer
 Dim strSQL As String, StrFolder As String
 Dim rngTargetcell As Range
 
 On Error GoTo ErrorHandler
  
  strSQL = "SELECT * FROM TestADO.txt"
  StrFolder = ActiveWorkbook.Path
  Set rngTargetcell = Range("A3")
  
    If rngTargetcell Is Nothing Then Exit Sub
    Set cn = New ADODB.Connection
    On Error Resume Next
    cn.Open "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _
        "DBQ=" & StrFolder & ";" & _
        "Extensions=asc,csv,tab,txt;FMT=Delimited(|)"
    
   'If cn.State <> adStateOpen Then Exit Sub
    
    Set rs = New ADODB.Recordset
    On Error Resume Next
    rs.Open strSQL, cn, adOpenForwardOnly, adLockReadOnly, adCmdText
    
    ' the field headings
    For f = 0 To rs.Fields.Count - 1
        rngTargetcell.Offset(0, f).Formula = rs.Fields(f).Name
    Next f
    rngTargetcell.Offset(1, 0).CopyFromRecordset rs ' works in Excel 2000 or later
    
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    
ErrorHandler:
    ' clean up
    If Not rs Is Nothing Then
        If rs.State = adStateOpen Then rs.Close
    End If
    Set rs = Nothing
    
    If Not cn Is Nothing Then
        If cn.State = adStateOpen Then cn.Close
    End If
    Set cn = Nothing
    
    If Err <> 0 Then
        MsgBox Err.Source & "-->" & Err.Description, , "Error"
    End If
End Sub
 

Excel Facts

Show numbers in thousands?
Use a custom number format of #,##0,K. Each comma after the final 0 will divide the displayed number by another thousand

Forum statistics

Threads
1,215,759
Messages
6,126,732
Members
449,333
Latest member
Adiadidas

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top