I have an SQL database and I want to update a specific table and specific fields.
I insert records from an Excel spreadsheet into another database I created that uses the dbo schema.
I wrote a stored procedure with an UPDATE in my play database that updates a table in the erp schema. If I execute the sp in SSMS it works. If I execute the sp from Excel it fails.
I update the Play database table is by executing a SELECT sp, returning the recordset to a spreadsheet and then creating and executing an UPDATE for each row. Of course, this take longer to accomplish.
Here is the code for the UPDATE stored procedure. For testing purposes, my procedure now returns the following line from SQL
SELECT #Rows AS i_Rows, DATEDIFF(MS,#Start, #End) / 1000 AS i_Seconds, (DATEDIFF(MS,#Start, #End) - (DATEDIFF(MS,#Start, #End)/1000)) AS i_Miliseconds
Sub ExecuteProc()
Dim o_Connection As ADODB.Connection, o_Recordset As ADODB.Recordset
Dim o_Command As ADODB.Command
Dim s_ConnString As String, s_StoredProcName As String, s_ProjectID, s_Name, s_SQL1 As String
Dim b_ProjHours, b_JobHours, b_Dates As Boolean
Dim ws As Worksheet
Dim l_row, l_count As Long
Dim t_Start, t_End As Date
Dim i_Seconds As Integer
' Determine the values of certain variables
With ActiveSheet
s_Name = .Name
b_JobHours = .chkHours.Value
b_Dates = .chkDates.Value
s_ProjectID = .Cells(15, "B").Value
End With
DataWS
' Make UpdateJobOper the selected sheet
With Worksheets("DATA")
.Select
.Cells.ClearContents
End With
' Create new Connection, Recordset, Command, and Connection String
Set o_Connection = New ADODB.Connection
Set o_Recordset = New ADODB.Recordset
Set o_Command = New ADODB.Command
s_ConnString = "Driver={SQL Server};SERVER=SQLSERVER;DATABASE=Play;UID=BIExcel;PWD=BIExcel;WSID=;"
On Error GoTo CloseConnection
' Open the Connection using the connection string
o_Connection.Open s_ConnString
' Stored Procedure Name and Project ID parameter
s_StoredProcName = "Play.dbo.BIspUpateJobOper"
' Define the command used to open the stored procedure
With o_Command
.ActiveConnection = o_Connection
.CommandType = adCmdStoredProc
.CommandText = s_StoredProcName
.Parameters.Append .CreateParameter("#ProjectID", adVarChar, adParamInput, 25, s_ProjectID)
End With
' Return the recordset using the command and paste it into the DATA worksheet starting at cell A2
Set o_Recordset = o_Command.Execute
Sheets("DATA").Range("A1").CopyFromRecordset o_Recordset
' Close the recordset and connection to the SQL Server
o_Recordset.Close
o_Connection.Close
On Error GoTo 0
On Error GoTo 0
DeleteDataWS
Exit Sub
CloseConnection:
Application.ScreenUpdating = True
DeleteDataWS
MsgBox "Failed to open SQL Connection", vbCritical, "SQL Error"
o_Connection.Close
End Sub
Public Function last_row_with_data(ByVal lng_column_number As Long, shCurrent As Variant) As Long
last_row_with_data = shCurrent.Cells(Rows.Count, lng_column_number).End(xlUp).Row
End Function
Sub DataWS()
' Add a new worksheet called DATA
' If the worksheet already exists, clear it
On Error GoTo AddSheet
With Sheets("DATA")
.Select
.Cells.ClearContents
End With
Exit Sub
' If it does not exist add it
AddSheet:
ActiveWorkbook.Sheets.Add.Name = "DATA"
End Sub
Sub DeleteDataWS()
On Error GoTo GetOutOfHere
Application.DisplayAlerts = False
Worksheets("DATA").Delete
Application.DisplayAlerts = True
GetOutOfHere:
End Sub
Related
I have some vba code that 'attempts' to loop through an array of DAO recordsets. When running the loop, I get a runtime error 'Oject required' at rst.MoveFirst. It seems that rst is not properly initialized but I'm not sure how to fix it. Maybe looping through an array of recordsets isnt even possible in this way I have never tried it before. The code runs from a custom class module. There is a bunch more code in the module but most of the important stuff I post below. A couple things I tried:
Set rst to a new recordset instance manually:
Set rst = New DAO.Recordset
Declaring the array outside the loop:
Set recordsets = Array(rstRechenwerte, rstZwischenwerte, rstZutaten)
' Loop through each recordset and insert data into Excel file
For Each rst In recordsets
Setting rst to an open recordset right before rst.MoveFirst:
For Each rst In Array(rstRechenwerte, rstZwischenwerte, rstZutaten)
Set rst = rst.OpenRecordset()
rst.MoveFirst
The three recordsets in the array are properly initialized, set and are not Nothing. I had previously written the code for each of the three recordsets seperately and it works that way. I am aware that I need to change the variable name XLColumn, but thats not really an issue atm. Its probably something bassic but I couldn't figure it out for a while now so I thought I'd just ask.
I am using the following libraries for which references are properly set:
Visual Basic for Applications
Microsoft Access 16.0 Object Library
OLE Automation
Microsoft Office 16.0 Access database engine Object
Library
Microsoft Excel 16.0 Object Library
Microsoft Office 16.0 Object Library
My version of Access:
Microsoft® Access® für Microsoft 365 MSO (Version 2301 Build 16.0.16026.20002) 32 Bit
The code:
Option Compare Database
Option Explicit
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim rsRes As DAO.Recordset 'rs of temp table (Output)
Dim rsZwi As DAO.Recordset 'rs of temp table (Zwischenwerte)
Dim rsRec As DAO.Recordset 'rs clone of subform Rechenwerte
Dim Recordset As Recordset
Dim rstRechenwerte As DAO.Recordset 'rs of tblRechenwerte
Dim rstZwischenwerte As DAO.Recordset 'rs of tblZwischenwerte
Dim rstZutaten As DAO.Recordset 'rs of tblZutaten
Dim RezeptID As Integer 'Current form active RezeptID
Dim RechengruppeID As Integer 'Current Form active RechengruppeID
Dim xlColumn As String 'Excel Column of Zutaten
Dim xlLastRow As Long 'Excel last row number after insertion
Dim xlColumn2 As String 'Excel Column one to the right of Zutaten
Dim k As Integer
Dim Export As Boolean 'Export the Excel File
Dim ExclExportPath As String 'Export location as string
Sub Calculate()
'***************************************************************************
'Purpose: Calculate a recipe based on Rechenwerte,
'save them temporarily and display them on a form.
'Inputs: None
'***************************************************************************
'***********************************************************************
' Preparations
'***********************************************************************
'Disable user input
Call mdlMiscFunctions.DisableKeyboardMouse(True)
'Clear temporary data tables for Results and Zwischenwerte
If Not rsRes.EOF Then Call ClearTableOnClose("tblTempResults")
If Not rsZwi.EOF Then Call ClearTableOnClose("tblTempZwischenwerte")
'Prevent prompt to save changes to excel
xlApp.DisplayAlerts = False
xlApp.Visible = False
'***********************************************************************
' Insert Data into Excel File
'***********************************************************************
Dim rst As DAO.Recordset
Dim xlCell As String
Dim xlFormula As String
Dim xlColumn As String
' Loop through each recordset and insert data into Excel file
For Each rst In Array(rstRechenwerte, rstZwischenwerte, rstZutaten)
rst.MoveFirst
If Not rst.EOF Then
Do Until rst.EOF
xlCell = rst!xlCell
xlSheet.Range(xlCell).Value = rst.Fields(1)
If rst.Fields.Count > 2 Then
xlFormula = rst!xlFormula
xlSheet.Range(xlCell).Offset(0, 1).Formula = xlFormula
xlSheet.Range(xlCell).Offset(0, 1).Value = xlSheet.Range(xlCell).Offset(0, 1).Value
Else
xlSheet.Range(xlCell).Offset(0, 1).Value = rst.Fields(2)
End If
rst.MoveNext
Loop
Else
Select Case rst.Name
Case "rstRechenwerte"
MsgBox "Error: Keine Rechenwerte vorhanden!", vbCritical
Case "rstZwischenwerte"
MsgBox "Error: Keine Zwischenwerte vorhanden!", vbCritical
Case "rstZutaten"
MsgBox "Error: Keine Zutaten vorhanden!", vbCritical
End Select
End If
Next rst
Class initialization is the following:
Private Sub Class_Initialize()
'***************************************************************************
'Purpose: Sub for initializing class variables
'Inputs: None
'***************************************************************************
'Values for variables 1 (Neccesary for recordsets)
RezeptID = Forms.frmCalcBatch.RezeptID 'RezeptID on current form
RechengruppeID = Forms.frmCalcBatch.RechengruppeID 'Rechengruppe on Current Form
'Initialize Objects
Set xlApp = CreateObject("Excel.Application")
Set xlWB = xlApp.Workbooks.Add
Set xlSheet = xlWB.Sheets("Tabelle1") 'Set xlSheet to the first sheet in the workbook
Set rsRes = CurrentDb.OpenRecordset("tblTempResults", dbOpenDynaset)
Set rsZwi = CurrentDb.OpenRecordset("tblTempZwischenwerte", dbOpenDynaset)
Set rsRec = Forms.frmCalcBatch.frmSubRechenwerteBox.Form.Recordset.Clone 'rs clone of Rechenwerte subform
Set rstRechenwerte = CurrentDb.OpenRecordset("SELECT Rechenwert, WertBezeichnung, XLCell FROM tblRechenwerte WHERE RechengruppeID = " & RechengruppeID)
Set rstZwischenwerte = CurrentDb.OpenRecordset("SELECT ZWBezeichnung, XLFormula, XLCell FROM tblZwischenwerte WHERE RezeptID = " & RezeptID)
Set rstZutaten = CurrentDb.OpenRecordset("SELECT Zutat, XLFormula, XLCell FROM tblZutaten WHERE RezeptID = " & RezeptID)
'Values for Variables 2 (recordsets neccesary for variables)
xlColumn2 = Split(rstZutaten!xlCell, "1")(0) 'extract excel column denominator for Zutaten
xlColumn2 = Chr(Asc(xlColumn2) + 1) 'Move one column to the right using Asc (A->B etc.)
'Settings:
If Forms.frmCalcBatch.cbExport = True Then
Export = True
ExclExportPath = GetExportPath
Else
Export = False
ExclExportPath = ""
End If
End Sub
You cannot New up a DAO.Recordset, the code will not even compile.
To loop through an array of recordsets, each recordset must initialized before it is added to the array.
For example:
Dim r1 As DAO.Recordset, r2 As DAO.Recordset, r3 As DAO.Recordset
Set r1 = CurrentDb().OpenRecordset("YourTableOrQueryName")
Set r2 = CurrentDb().OpenRecordset("YourTableOrQueryName")
Set r3 = CurrentDb().OpenRecordset("YourTableOrQueryName")
Put the recordsets now in the array.
Dim arr As Variant
arr = Array(r1, r2, r3)
To loop, you need to use a For loop and either access the recordset from the array directly, or declare another recordset variable to hold the iterating recordset.
Through an iterator variable:
Dim r As DAO.Recordset, i As Integer
For i = LBound(arr) To UBound(arr)
Set r = arr(i)
If Not r.EOF Then
r.MoveFirst
Debug.Print r.RecordCount
End If
Next i
Access it directly from the array:
For i = LBound(arr) To UBound(arr)
If Not arr(i).EOF Then
arr(i).MoveFirst
Debug.Print arr(i).RecordCount
End If
Next i
Though I fail to see why you need to have 3 recordsets in memory at the same time. Personally, I would offload the work that needs to be done in the loop to a separate function and pass the recordset as parameter. The function itself would return a success/failed status, so you can take the appropriate action based on the result.
Another approach would be to store the source names in the array, and create the recordset on demand during the loop.
Hope this helps.
Here is the VBA code I have in the module:
Private Sub Workbook_Open()
Dim adoDBConn As New ADODB.connection
Dim adoDbRs As New ADODB.Recordset
Dim selectCmd As New ADODB.Command
adoDBConn.Open "Provider=SQLOLEDB;Data Source=LAPTOP-N0CT1GQ5;Initial Catalog=Interest_Analysis;User Id = ***;Password = ***;"
selectCmd.ActiveConnection = adoDBConn
selectCmd.CommandText = "County, cntyvtd, Name, Votes FROM 2020_General_Election_Returns_import_to_SQL"
Set adoDbRs = selectCmd.Execute(, , adCmdText)
Dim cellRange As Range
Set cellRange = Range(Cells(2, 2), Cells(Row.Count, 1)).EntireRow
cellRange.ClearContents
'The Worksheet tab is called "Data"
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Data")
ws.Activate
If adoDbRs.EOF = False Then ws.Cells(2, 2).CopyFromRecordset adoDbRs
ws.Cells(1, 2) = "County"
ws.Cells(1, 3) = "cntyvtd"
ws.Cells(1, 4) = "Name"
ws.Cells(1, 5) = "Votes"
adoDbRs.Close
Set adoDbRs = Nothing
Set selectCmd = Nothing
adoDBConn.Close
Set adoDBConn = Nothing
End Sub
What I'm doing is using an ADODB connection to connect to SQL Server in Microsoft Excel and using VBA code to interact with the server so that the data can populate in an Excel sheet. I got much of the code template from a website, but have been running into a lot of errors and the debugger keeps pointing at different lines. Right now, it's pointing at the Set adoDbRs = selectCmd.Execute() line and saying Incorrect syntax near ',' and it would also go to the If adoDbRs.EOF = False and say Object not found. I might be missing a foundational statement or something I need to start with, so let me know what the issue is. Thank you!
To debug VBA and figure out how to pull SQL server data into an Excel spreadsheet.
This worked fine for me (against Oracle, but SQL server should work the same way)
Private Sub SOTest()
Dim adoDBConn As New adodb.Connection
Dim adoDbRs As adodb.Recordset 'no `New` here
Dim selectCmd As New adodb.Command
Dim ws As Worksheet, f As adodb.Field
Set ws = ThisWorkbook.Worksheets("Data")
adoDBConn.Open "connection string here"
selectCmd.ActiveConnection = adoDBConn
selectCmd.CommandText = "select * from myTable"
Set adoDbRs = selectCmd.Execute(, , adCmdText)
'clear the output range
ws.Range(ws.Cells(1, 2), ws.Cells(ws.Rows.Count, 15)).ClearContents
ResultsToSheet adoDbRs, ws.Cells(1, 2)
ws.Activate
adoDbRs.Close
adoDBConn.Close
End Sub
'Place a recordset contents on a worksheet (incl. headers)
' starting at `rng`
Sub ResultsToSheet(rs As adodb.Recordset, rng As Range)
Dim c As Range, f As adodb.Field
Set c = rng.Cells(1) ' top left
For Each f In rs.Fields
c.Value = f.Name 'write the field header
Set c = c.Offset(0, 1) 'next header cell
Next f
If Not rs.EOF Then
'write the data starting on the next row
rng.Cells(1).Offset(1).CopyFromRecordset rs
End If
End Sub
I have been using this code for some time and it works. As a matter of fact it works with a basic query. It just does not work with my new Stored Procedure. I can run the stored procedure manually. in SSMS and get my results. I thought that the error was when I was not getting data back so I added the . . . If myRS1.EOF Then . . . still getting the 3704 runtime error.
Here is my Excel (2013) Code
Private Sub cmdOK_Click()
Dim myStartDate, myEndDate
Dim myInsuranceCode
Dim objAD, objUser
Dim myDisplayName, myLastRow
Dim myMessage, myStyle, myTitle, myResult
Dim mySQL As String
Dim myConn
Dim myCmd
Dim myRS1
Dim myRange, myNamedRange, myCheckRange As Range
Dim X, Y, z
Dim myPercent, myLowEnd, myHighEnd
Dim myValue1, myValue2, myValue3, myValue4, myValue5, myValue6, myValue7, myValue8
Dim myCheckValue
Dim myHeaderRow, myDataRow, myLastColumn
'SET THESE ACCORDING TO THE REPORT. THE FIRST TWO MIGHT NOT NEED ANY CHANGES
myHeaderRow = 2
myDataRow = 3
myLastColumn = 22
'SETUP DATABASE OBJECTS
Set myConn = New ADODB.Connection
Set myCmd = New ADODB.Command
Set myRS1 = New ADODB.Recordset
Application.StatusBar = True
Application.StatusBar = "Connecting to SQL Server"
'GET DATES FROM TEH FORM AND SET SQL STATEMENT
myStartDate = frmMain.txtStartDate
myEndDate = frmMain.txtEndDate
'RUN INSURANCE STORE PROCEDURE
'SEPERATE THE INSURANCE CODE WITH A |
myInsuranceCode = "S19|S22"
mySQL = "dbo.BMH_rpt_PATIENTS_INSURANCE_LISTING '" & myStartDate & "', '" & myEndDate & "', '" & myInsuranceCode & "'"
'mySQL = "SELECT * FROM dbo.BETHESDA_ADMIT_SOURCE"
'HIDE THE FORM
frmMain.Hide
'GET THE USER THAT IS SIGNED IN
Set objAD = CreateObject("ADSystemInfo")
Set objUser = GetObject("LDAP://" & objAD.UserName)
myDisplayName = objUser.DisplayName
'OPEN CONNECTIONS TO THE DATABASE
myConn.ConnectionString = "Provider=SQLOLEDB;Data Source=mySQLServer;Initial Catalog=myDatabaseName;User ID=user;Password=xxxxxxxx;Connection Timeout=300;"
myConn.Open
'SET AND EXECUTE SQL COMMAND
Set myCmd.ActiveConnection = myConn
myCmd.CommandText = mySQL
myCmd.CommandType = adCmdText
Application.StatusBar = "Running Stored Procedure " & mySQL
myCmd.CommandTimeout = 3000
'OPEN RECORDSET
Set myRS1.Source = myCmd
myRS1.Open
'CHECK TO MAKE SURE WE ARE NOT AT THE BOTTOM OF THE SHEET COULD MEAN THERE WAS NOT DATA LAST TIME.
'THIS SAME CODE WILL REPEAT FOR THE DATA TAB
'*********** DATA *************
'CHECK TO MAKE SURE THERE IS DATA
If myRS1.EOF Then <---- THIS IS THE LINE I AM GETTING THE ERROR
Cells(myDataRow, 1).Value = "No Data Qualifies"
myMessage = "No data qualifing for your request " & mySQL
myTitle = "No Data"
myStyle = vbCritical + vbOKOnly
myResult = MsgBox(myMessage, myStyle, myTitle)
Exit Sub
End If
'SELECT THE SHEET TO CLEAR OUT THE OLD data on DATA
'IF THIS IS NOT SET ON THE SEEHET IT WILL FAIL
Set myTable = Sheets("DATA").ListObjects("DATA")
If Cells(myDataRow, 1).Value <> "" Then
myTable.DataBodyRange.Rows.Delete
End If
'COPY THE DATA TO EXCEL
Application.StatusBar = "Copying the new data."
Sheets("DATA").Cells(myDataRow, 1).CopyFromRecordset myRS1
Cells(1048576, 1).Select
Selection.End(xlUp).Select
myLastRow = ActiveCell.Row
'Application.StatusBar = "Naming the new DATA range"
'ActiveWorkbook.Names.Add Name:=myNamedRange, RefersTo:=Range(Cells(myHeaderRow, 1), Cells(myLastRow, myLastColumn))
myTable.Resize Range(Cells(myHeaderRow, 1), Cells(myLastRow, myLastColumn))
End Sub
*** This is all the VBA Code now. It is failing on the myRS1.EOF line so none of the other code even runs.
As you can see I have two mySQL statements. The first one is not working, but the second one works no issue.
If I run the SP from SSMS or even take the mySQL that is generated it runs fine in SSMS.
Here is the SP
--EXAMPLE
-- dbo.BMH_rpt_PATIENTS_INSURANCE_LISTING '11/01/2020', '11/30/2020', 'S19|S22'
ALTER PROCEDURE [dbo].[BMH_rpt_PATIENTS_INSURANCE_LISTING]
#StartDate AS DATETIME,
#EndDate AS DATETIME,
#Insurance AS VARCHAR(MAX)
AS
/** GET THE INSURANCE CODES **/
SELECT VALUE
INTO #INSURANCE
FROM STRING_SPLIT(#Insurance, '|')
/** GET THE PATIENTS FOR THE LIST **/
SELECT vv.pt_id AS 'Patient Account',
vv.alt_med_rec_no AS 'MRN'
FROM smsdss.vst_v AS vv
WHERE vv.pyr_cd IN (SELECT * FROM #INSURANCE)
AND vv.start_full_date BETWEEN #StartDate AND #EndDate
AND vv.tot_bal_amt <> 0
I am trying to query a database using Excel VBA and write to a sheet. The VBA code I have works fine for one server/database, but when I try to pull from a different database it messes up.
When I run this on this database, I get an error stating "Operation is not allowed when object is closed." on With mrs line. I don't understand why the object is closed when I opened it two lines before.
SQL query has nocount on and ansi_warnings off.
Here is the associated VBA Code:
Dim strFileContent As String
Dim massiveString As String
Sub runSelectedQueries()
Call runQuery(Sheet3, "dbp07", "OLBRET", "C:\Queries\query.sql")
End Sub
Private Sub runQuery(outputSheet As Worksheet, serverVar As String, databaseVar As String, queryLoc As String)
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
sconnect = "Provider=SQLOLEDB;driver={SQL Server}; server=" & serverVar & "; Integrated Security=SSPI; database=" & databaseVar & ";"
MsgBox (sconnect)
'run readFile sub
readAnyFile (queryLoc)
'parse SQL file into string
sSQLString = massiveString
Conn.Open sconnect
mrs.Open sSQLString, Conn
'write in the master record set (mrs) into a sheet
With mrs
For i = 1 To .Fields.Count
outputSheet.Cells(1, i) = .Fields(i - 1).Name
Next i
End With
outputSheet.Range("A2").CopyFromRecordset mrs
'Close Recordset
mrs.Close
'Close Connection
Conn.Close
End Sub
'reads any file as input (text) not binary using EOF, stripping the metadata at begining of a file
Sub readAnyFile(queryLoc As String)
Dim FileNum As Integer
Dim DataLine As String
massiveString = ""
FileNum = FreeFile()
Open queryLoc For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine ' read in data 1 line at a time
massiveString = massiveString + DataLine
Wend
massiveString = Right(massiveString, Len(massiveString) - 2)
MsgBox ("Read Successfully")
MsgBox (massiveString)
End Sub
When I debug and push out the SQL code that is read from a file, I get exactly what is in SQL Server Management Studio. The SQL statement runs fine in MS Query, Python and SQL Server Management Studio as parsed by VBA so I don't think that's the issue but I could post it.
I have an excel sheet with 10 columns with headers. For a column I can have the data as "FF5" or else 620. The sheet name is IODE.
I am trying to import this data from SSIS Import data wizard into the database of table IODE.
On selecting source and destination in the wizard, when I click on PREVIEW DATA in Select Source Tables and Views window, I see the column with 620 as null. After importing this data, the table will have the NULL Instead of 620.
The data type for this column in table is nvarchar(50), I tried many data types like varchar(100), text/..
Only alpha numeric data is accepting.
I didn't write any code for this.. I am just trying to import data from excel sheet to a table.
Please help me in solving this
Thanks
Ramm
Do you mean that you have either FF5 or 620 as the values for that column meaning you have one or the other and nothing else or are there blank fields in that column as well?
I tried reading the excel by using the Excel library reference in VB6.0.
As SSIS Import Wizard treats NUMERIC as NULL when the data is exported to the SQL Table.
This procedure works very well for the data insertion and also for the other database operations.
Private Sub AccessExcelData()
On Error GoTo errHandler
Dim oXLApp As Excel.Application'Declare the object variable
Dim oXLBook As Excel.Workbook
Dim oXLSheet As Excel.worksheet
Dim strFileName As String
Dim lCount As Long
Dim strSCDName As String
Dim strICDName As String
Dim intSource_Index As Integer
Dim strInput_Port As String
Dim strLabel As String
Dim strSDI_CID As String
Dim intWordBitNO As Integer
Dim strFilter_Type As String
Dim strPgroup_Input As String
Dim strParagraph_Input As String
Dim strSQL As String
Dim sConnString As String
Dim cnTest As New ADODB.Connection
Dim rsTempRecordset As New ADODB.Recordset
Dim objDataAccess As New FmmtDataAccess.clsDataAccess
Dim strxmlResult As String
objDataAccess.Intialize ConString
strFileName = App.Path & "\IODE.xls"
sConnString = "Server=uasql\commonsql;Database=accounts;Driver=SQL Server;Trusted_Connection=Yes;DSN=uasql\commonsql"
With cnTest
.ConnectionString = sConnString
.ConnectionTimeout = 4
.CursorLocation = adUseClient
.Open
End With
' Creating part of the excel sheet.
Set oXLApp = CreateObject("Excel.Application")
'Create a new instance of Excel
oXLApp.Visible = False
'Donot Show it to the user
Set oXLBook = oXLApp.Workbooks.Open(strFileName) 'Open an existing workbook
Set oXLSheet = oXLBook.Worksheets(1) 'Work with the first worksheet oXLSheet.Activate
With oXLApp
For lCount = 2 To oXLSheet.UsedRange.Rows.Count
strSCDName = .Cells(lCount, 1).Value
strICDName = .Cells(lCount, 2).Value
intSource_Index = .Cells(lCount, 3).Value
strInput_Port = .Cells(lCount, 4).Value
strLabel = .Cells(lCount, 5).Value
strSDI_CID = .Cells(lCount, 6).Value
intWordBitNO = .Cells(lCount, 7).Value
strFilter_Type = .Cells(lCount, 8).Value
strPgroup_Input = .Cells(lCount, 9).Value
strParagraph_Input = .Cells(lCount, 10).Value
'strSQL = "Insert into XYX () values (strSCDName ..... ) Here any DB related queries can be used
rsTempRecordset.Open strSQL, cnTest, adOpenForwardOnly, adLockReadOnly Next
End With
' Closing part of the excel sheet.
oXLApp.Visible = False 'Donot Show it to the user
Set oXLSheet = Nothing 'Disconnect from all Excel objects (let the user take over)
oXLBook.Close SaveChanges:=False 'Save (and disconnect from) the Workbook
Set oXLBook = Nothing
oXLApp.Quit 'Close (and disconnect from) Excel
Set oXLApp = Nothing
Exit SuberrHandler:
MsgBox Err.Description
Screen.MousePointer = vbNormalEnd Sub
With this procedure the excel records can be read from vb applicatoin and can be inserted into existing table in the SQL database.
Thanks
Ramm