Hi Fazza,
Thanks for the sample. I did some tests of my own to come up with the following. This time, with early binding...
-----------------------------------------------
The following behavior was noted during my test:
1) Using a named range with update statements appears to be unpredictable as the named range
may be moved or lost. This should pose no problem with select queries.
2) Trying to use a single cell as a recordset fails, with or without headers. I found that in either case I could
reference the cell I am interested in updating, along with the cell below it or above it - in the latter case
"pretending" there is a header cell.
-- Alex
-----------------------------------------------
hirvenhuuli,
Please pay close attention to the comments at the beginning of the subroutine
about setting a reference to the ADO library.
Code:
Sub ChangeDataInSingleCell()
'---------------------------------
'USER: Please make sure you set references to the ADO object Library
' 1. In the Visual Basic window select Tools on the main menu
' 2. Then from the Tools menu select References...
' 3. Then click the box for Microsoft ActiveX Data Objects 2.8 or higher
'---------------------------------
Dim objRecordset As ADODB.Recordset
Dim stConn As String
Dim stSQL As String
Dim workbookVar As String
Dim strTarget As String 'Worksheet and cell address - in brackets with sheet name suffixed with a $
Dim newValueVar As Double
'-----
'Note:
'In referencing the sheet and cell to update,
' we are interested in one cell. But we "pretend" there is a
' field header above it - ADO seems to require at least two cells
'-------------------------------------------------------------------
workbookVar = "C:\MyBook.xls"
strTarget = "[Sheet1$E3:E4]"
newValueVar = 2.7182
'Create the connection string.
stConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
workbookVar & ";Extended Properties=Excel 8.0;"
Debug.Print stConn
'Create the SQL query string
stSQL = "SELECT * FROM " & strTarget
Debug.Print stSQL
Set objRecordset = New ADODB.Recordset
Call objRecordset.Open(stSQL, stConn, CursorTypeEnum.adOpenDynamic, _
LockTypeEnum.adLockOptimistic, CommandTypeEnum.adCmdText)
'Only one record to be updated
If Not objRecordset.EOF Then
objRecordset.Fields(0).Value = newValueVar
objRecordset.Update
End If
Set objRecordset = Nothing
End Sub