Link to home
Start Free TrialLog in
Avatar of JMSSystems
JMSSystems

asked on

ADO Code Won't Delete Excel Rows

I have an Access 2000 database.  Ultimately, I want to take data out of an Access table, and replace the data on a specific Excel 2000 file and worksheet.  For now, I have a simple example, shown below, where I open the excel file, try to delete the rows that are there, and then write some new excel rows with hardcoded data (not data from the access table).  The code seems to work, except when it tries to delete the existing excel rows.  It fails on the line that says:  oRS.UpdateBatch

The error message is:
Run-time error: '-2147467259(80004005)':
[Microsoft][ODBC Excel Driver] Deleting data in a linked table is not supported by this ISAM.

*** WHAT DO I HAVE TO DO TO GET THE DELETE TO WORK? ***

Here is the code.  All you need is an excel file in a directory called C:\JMS\expenses.xls and an Access database with a table called AvgRty4EachCell.

Private Sub Command37_Click()

'Purpose: Post data from an Access table to an Excel spreadsheet using ADO.

Dim oConn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim db As Database
Dim rs As Recordset
Dim fldCurrent As Field
Dim strWorkbookName As String
Dim strWorkDir As String
Dim ColCount, RowCount As Integer

Set db = CurrentDb

'Access Table.
Set rs = db.OpenRecordset("AvgRty4EachCell", dbOpenSnapshot)

'Excel Spreadsheet.
strWorkbookName = "c:\JMS\expenses.xls"
strWorkDir = "c:\JMS"

' Create and open a new ADO Connection
Set oConn = New ADODB.Connection

oConn.Open "Provider=MSDASQL.1;Persist Security Info=False;Extended Properties=DBQ=" & strWorkbookName _
& ";DefaultDir=" & strWorkDir & ";Driver={Microsoft Excel Driver (*.xls)};DriverId=790;FIL=excel 8.0;MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;ReadOnly=0;SafeTransactions=0;Threads=3;UID=admin;UserCommitSync=Yes;"

' Create the Recordset
Set oRS = New ADODB.Recordset
oRS.CursorLocation = adUseClient


' Open the Recordset using the Sheet Name
oRS.Open "Select * from `Sheet1$A1:E10`", oConn, adOpenStatic, adLockBatchOptimistic, adCmdText

MsgBox "Beginning Record Count: " & oRS.RecordCount

'Delete ALL rows on excel spreadsheet.
RowCount = oRS.RecordCount

Do While RowCount > 0
    oRS.MoveLast
    oRS.Delete
    RowCount = RowCount - 1
Loop
oRS.UpdateBatch

'Post Access table field names as the Excel spreadsheet column headings.
ColCount = 0
oRS.AddNew
With rs
    For Each fldCurrent In .Fields
        oRS(0).Value = fldCurrent.Name
        ColCount = ColCount + 1
    Next fldCurrent
End With


' Update last row
oRS.MoveLast
oRS(0).Value = -1
oRS.Update

' Add a new row
oRS.AddNew
oRS(0).Value = 7
oRS(1).Value = 8
oRS(2).Value = 9
oRS.Update

'Debug.Print oRs.RecordCount
MsgBox "Ending Record Count: " & oRS.RecordCount

rs.Close
oRS.Close
oConn.Close

'Destroy the objects to free resources
Set rs = Nothing
Set oRS = Nothing
Set oConn = Nothing

End Sub
Avatar of Richie_Simonetti
Richie_Simonetti
Flag of Argentina image

Since it is linked, difficult arises.
Did you try cleaning excel sheet throghout COM before update?
Hearing...
There are a several operations that you cannot perform on Microsoft Excel worksheets or workbooks through the Microsoft Excel installable ISAM, Delete is one of them.

Providing the cells do not have any formulas you can clear them or modify them.  Instead of deleting try overwriting.

If this solution does not work for you. You may have to resort using VBA from within Excel.
Avatar of JMSSystems
JMSSystems

ASKER

The only thing that seems to work when it comes to posting values to the excel spreadsheet, is when I post numbers.  My hardcoded updates using numbers works fine.  However, when I try to post any kind of string, "ABC" for example, I get an error message, with the usual helpful Microsoft type explanation:

Run-time error '-2147217887(80040e21)':
Errors Occured.

Why can't I post character data?
I think we are talking about two separate issues:
1.  Error Handling.  Are you checking the errors collection for all the errors if more than one?

2.  Updating cells in Excel. Providing there is no formaula in those cells it should be pretty straight forward to update.  Here is an example of something I just did:

Option Explicit

Private Sub Command1_Click()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim I As Integer

Set cn = New ADODB.Connection
With cn
   .ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\Temp.xls;Extended Properties='Excel 8.0;HDR=No'"
   .Open
End With

Set rs = New ADODB.Recordset
With rs
   .Source = "Select * from [Sheet1$A1:D10]"
   .ActiveConnection = cn
   .CursorType = adOpenDynamic
   .LockType = adLockOptimistic
   .Open Options:=adCmdText
   I = 64
   Do While Not .EOF
      I = I + 1
      .Fields(1).Value = String$(10, I)
      .Update
      .MoveNext
   Loop
   .Close
End With
Set rs = Nothing
cn.Close
Set cn = Nothing

End Sub
Well, I'm getting closer, and I appreciate the help very much.  However, there is one problem with the code you listed.  Because it references rs.Fields(1), it puts data starting in column b of the worksheet.  Yet, when I try to say rs.Fields(0) to post to column A, it says "Numeric Overflow" and then "Type Mismatch".  Try changing your code to rs.Fields(0) and running it and you will see what I mean.  How then do I start writing data to column A of the spreadsheet?
ASKER CERTIFIED SOLUTION
Avatar of Anthony Perkins
Anthony Perkins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Okay, thanks for your help.  I still had a problem in my code.  I was first writing the Access table field names to the first row of the spreadsheet for use as headers.  I would then post the data starting in row 2.  I ran into a problem when the header was text (obviously) but the data was numeric (double to be exact).  For example, the spreadsheet needs to look as follows:

FieldName1    FieldName2
ABC               123.45
DEF               456.78

To finally get it to work, I changed the Connect string to say HDR=Yes, removed the code posting the Access table field names to row 1, and posted only the data.  Now, everything works fine.  When HDR=Yes, .Movefirst takes you to row 2 of the spreadsheet, thus leaving whatever headers were there to begin with alone.
Thanks for your help.  I appreciated your timely responses.