Solved

ADO Code Won't Delete Excel Rows

Posted on 2001-08-03
8
1,274 Views
Last Modified: 2007-11-27
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
0
Comment
Question by:JMSSystems
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 16

Expert Comment

by:Richie_Simonetti
ID: 6350580
Since it is linked, difficult arises.
Did you try cleaning excel sheet throghout COM before update?
Hearing...
0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 6350821
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.
0
 

Author Comment

by:JMSSystems
ID: 6351640
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?
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 6352512
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
0
 

Author Comment

by:JMSSystems
ID: 6354647
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?
0
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 250 total points
ID: 6355681
It has nothing to do with the column I update.  I could have chosen any or all.  The problem has to do with:
A. The data in the spreadsheet contains formulas or
B. Contains a numeric data incompatible with the character data you are now trying to replace it with.

When you open the recordset, I suspect ADO makes a judgement call as to what type of data it contains.

Just to satisfy yourself, assuming you have nothing in Sheet 2, input some character data in the first column and ten rows and then run the code, but first change Sheet1 to Sheet2.  Then change the code to numeric data.

For the record, I did run the code pointing at column A.
0
 

Author Comment

by:JMSSystems
ID: 6358276
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.
0
 

Author Comment

by:JMSSystems
ID: 6358282
Thanks for your help.  I appreciated your timely responses.
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses
Course of the Month5 days, 11 hours left to enroll

627 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question