I'm testing a small program to write some data to a SQL Server 2008 database. This is the code:
Dim MyConn As ADODB.Connection
Dim MyRecSet As ADODB.Recordset
Dim st1 As Integer
Set MyConn = New ADODB.Connection
MyConn.ConnectionString = "Provider=sqloledb;" & _
"Data Source=xxx\SQLEXPRESS2;" & _
"Initial Catalog=db;" & _
"User Id=sa;" & _
"Password=xxx"
MyConn.Open
st1 = 5
MyConn.Execute("INSERT INTO steen (steen1) VALUES (st1)")
MyConn.Close
However, I'm getting the error: Invalid column name 'st1'.
I have no idea why I'm getting this erro.
When I change the query to this:
INSERT INTO steen (steen1) VALUES (5)
It works perfectly.
Does anyone have an idea why I'm getting the error?
Thanks
try:
MyConn.Execute("INSERT INTO steen (steen1) VALUES ("& st1 & ")")
Or:
st1 = 5
Dim StrQuery As String
StrQuery = "INSERT INTO steen (steen1) VALUES ("& st1 & ")"
MyConn.Execute(StrQuery)
Related
I am trying to insert data from vba to sql server but its throwing up an error please help me.
Excel_SQL()
Dim con As ADODB.Connection
Set con = New ADODB.Connection
con.Open "Driver={SQL Server};Server=ev01LAP130\MSSQLSERVER1;Database:=Sample 1,Uid=Meera;Password=meeraagrawal"
Dim slry As Variant
Dim my_table, Data As Range
Set my_table = Range("A1").CurrentRegion
For Each Data In my_table.Rows
Name = Data.Cells(2, 1).Value
slry = Data.Cells(2, 2).Value
Sql = "insert into emp values('" & Name & "'," & slry & ")"
' MsgBox Sql
con.Execute Sql
Next Data
con.Close
End Sub
I need select data from database, using Excel. I want to select only one column from database and I need use where statement (to select only data which have the same unique value as data in Excel sheet)
I tried this
Sub DB_RTVresult()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim myRes As ADODB.Recordset
Server_Name = "123" ' Enter your server name here
Database_Name = "DBName" ' Enter your database name here
User_ID = "UserName" ' enter your user ID here
Password = "Pass" ' Enter your password here
Set myCon = New ADODB.Connection
Worksheets(2).Select
LastRow = GetRowCnt
For bl = LastRow To 5 Step -1
myCon.ConnectionString = "Driver={SQL Server};Server=" & Server_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";Database=" & Database_Name & ";"
myCon.Open
SQLStr = "SELECT [RTV_RESULT]" & _
"FROM [WSCZWMS].[WSCZWMS].[OMEGA_E2E_REPORT] WHERE [SME_TRACK_NO] ='" & Cells(bl, "CC").Value & "'"
Set myRes = myCon.Execute(SQLStr)
Worksheets("HelpTables").Range("E2" & Rows.Count).End(xlUp).Offset (1)
StrQuery = "OMEGA_SPEQ_REPORT"
myCon.Close
Set myRes = Nothing
Set myCon = Nothing
Next
End Sub
But when I run it, it writes Application-define or object-define error.
and colored this line
Worksheets("HelpTables").Range("E2" & Rows.Count).End(xlUp).Offset(1).CopyFromRecordset myRes
This line dave the select data into first empty row in column E, (start on 3rd row)
Do you have any idea how to solve this?
The reason for your issue is, that you are already referring to the Row in your .Range("E2" & Rows.Count) .
If you modify the mentioned line to the following, it should work properly:
Worksheets("HelpTables").Cells(Rows.Count, 5).End(xlUp).Offset(1).CopyFromRecordset myRes
The 5 in .Cells(Rows.Count, 5) is for the fifth column ('E').
I am not sure, but it seems that your excel objects Cells dans Rows should be affected and your sheets selected.
I would have writen
For b1=...
Worksheets(2).select
...
... Worksheets(2).cells(b1,"CC").value
...
Worksheets("HelpTables").select
Worksheets("HelpTables").Range("E" & _
Worksheets("HelpTables").Range("E:E").Rows.Count).End(xlUp).Offset(1) ...
...
NB :
"CC" is the name of a Excel value ?
Do you want Range("E2" & rows.count) to go to E2100 if there are 100 rows ? That's why I wrote "E" and not "E2" in my proposition. But may be you wanted (... rows.count+2) ?
Hope it helps.
Pierre.
I have some problem when I deal with MS Access. I am using SQL Server and MS Access together.
I try to insert data into a new table.
First, this program asks me to add an item to the list (it is like temporary table). And then, there is another submit button which confirms the data (this step is needed and it is not inefficient one. Please do not ask about this step).
To add data to the list, I use a stored procedure. But I do not know what do I need to do to submit the data again.
Here is my code:
Dim rs As ADODB.Recordset
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn
cmd.ActiveConnection = conn
Set rs = New ADODB.Recordset
rs.Open "Insert into dbo.Blend values(List731.Column(1, introw),List731.Column(2, introw),TextRequestNo.Value, List731.Column(3, introw),List731.Column(4, introw),List731.Column(5, introw))"
conn.Close
Set rs = Nothing
MsgBox "Done"
When I run with this code, I get this error:
I think there is some missing in my code but I do not know how to proceed.
Is there anyone who can give me some information about this?
There are many ways to do this kind of thing. Something like this should get the job done.
Sub MoveDateFromAccessToSQLServer()
Dim adoCN As ADODB.Connection
Dim sConnString As String
Dim sSQL As String
Dim lRow As Long, lCol As Long
sConnString = "Provider=sqloledb;Server=servername;Database=NORTHWIND;User Id=xx;Password=password"
Set adoCN = CreateObject("ADODB.Connection")
'adoCN.Open sConnString
'Assumes that you have Field1, Field2 and Field3 in columns A, B and C
'Text values must be enclosed in apostrophes whereas numeric values should not.
sSQL = "INSERT INTO YOUR_TABLE (FIELD1, FIELD2, FIELD3) " & _
" VALUES (" & _
"'" & Column(1, introw) & "', " & _
"'" & Column(2, introw) & "', " & _
"'" & Column(3, introw) & "')"
adoCN.Execute sSQL
adoCN.Close
Set adoCN = Nothing
End Sub
I have a excel workbook that is a project plan template, that the PM fills in information and it gets loaded into a sql database. Currently the process if via a batch process that loads two tables(1 with 1 row of data and the other with multiple records). I am changing it to be a direct insert from excel into sql server via vba. I have the insert working but each table has a project id column which is the PK. The pm may update and save this file multiple times. The tables get updated with the most recent save information. I have solved this by adding a delete statement into my code and then inserting the updated record. This works great for the table with 1 record but I can't get the table with multiple records to work. It deletes the records and goes through the first loop of the insert but then goes back to the delete and removes the records.
I have attached the code for the multiple table delete and insert. Can someone tell me what I am doing wrong?
Public Sub exportprojdetaildata()
Dim stSQL As String
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConn As String
Dim iRowNo As Integer
Dim targetedFieldNames As Variant
Dim rowData As Variant
Dim lastrow As Long
Dim sql As String
Dim i As Integer
Dim cvt As Double
Dim aField As String
Dim compare As Variant
Dim value As Variant
Dim dvalue As Long
With Sheets("Data")
lastrow = .Range("A:A").Find(what:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
'Open a connection to SQL Server
conn.Open _
"Provider=SQLOLEDB;Data Source=PWIRTPAUDD1HV8;Initial Catalog=STAR;User Id=STAR_USER;Password=dcistarrtp"
'Skip the header row
iRowNo = 2
targetedFieldNames = Join(WorksheetFunction.Transpose(wks_TargetFieldNames.Range("targetedFieldNames").value), "," & vbNewLine)
Do While iRowNo <= lastrow
rowData = wks_BackgroundData.Range("A" & iRowNo & ":AV" & iRowNo).value
compare = wks_BackgroundData.Range("AV2").value
'Generate and execute sql statement to import the excel rows to SQL Server table
With rs
.ActiveConnection = conn
.Open "Select proj_id from dbo.STAR_DC_INITIAL_ProjectDetails_ExcelDevCopy where proj_id = " & compare
wks_BackgroundData.Range("BA2").CopyFromRecordset rs
.Close
End With
value = wks_BackgroundData.Range("BA2").value
If compare = value Then
sql = "delete from dbo.STAR_DC_INITIAL_ProjectDetails_ExcelDevCopy where proj_id = " & value
conn.Execute sql
Else
sql = "insert into dbo.STAR_DC_INITIAL_ProjectDetails_ExcelDevCopy ("
sql = sql & targetedFieldNames
' Debug.Print sql
sql = sql & ") values (" & vbNewLine
' Debug.Print sql
'couldn't do transpose since rowData represents a row, not a column
For i = 1 To UBound(rowData, 2)
aField = Replace(rowData(1, i), "'", "''")
'escape single quotes
Select Case i
Case 1, 6, 16, 17, 23 To 47
' cvt = CDbl(aField)
If aField = vbNullString Then
sql = sql & "Null," & vbNewLine
Else
sql = sql & aField & "," & vbNewLine
End If
Case 2 To 5, 7 To 15, 18 To 22
sql = sql & "'" & aField & "', " & vbNewLine
Case 48
If aField = vbNullString Then
sql = sql & "Null"
Else
sql = sql & aField
End If
End Select
Next i
sql = sql & ");"
'sql = sql & "');"
' End If
conn.Execute sql
iRowNo = iRowNo + 1
Loop
End If
conn.Close
Set conn = Nothing
End With
End Sub
It's difficult to be sure without seeing the data that you're trying to save, but I suspect you have a logic error.
The value for rowData is built up dynamically in a loop. which is correct.
rowData = wks_BackgroundData.Range("A" & iRowNo & ":AV" & iRowNo).value
but the values for compare and value are always read from the same location inside the loop. So the delete statement will be executed over and over again.
compare = wks_BackgroundData.Range("AV2").value
value = wks_BackgroundData.Range("BA2").value
Should compare and value not also be read dynamically?
compare = wks_BackgroundData.Range("AV" & iRowNo).value
value = wks_BackgroundData.Range("BA" & iRowNo).value
Or
you should move the delete statement outside of the loop, to ensure that it's only executed once
Or
you should keep a flag that will indicate that the delete has already been executed, and not execute it again.
hasExecuted = false <- OUTSIDE THE LOOP
...
...
If compare = value and hasExecuted = false Then
sql = "delete from dbo.STAR_DC_INITIAL_ProjectDetails_ExcelDevCopy where proj_id = " & value
conn.Execute sql
hasExecuted = true
...
...
Also, I don't think you should have a IF x=y THEN delete ELSE INSERT. Should it not be IF x=y THEN delete, and always INSERT. With the else, it will only insert if the record didn't exist, but if it deleted the record, it will never insert the new one.
Hope that helps a bit
Avoid using VBA for new development work. If you need to constantly take this Excel document and insert it into a SQL Server database, then use SSIS and some C# to easily make it a scheduled task via the SQL Agent, or simply do as the screen shot below suggests, which is a no-code and easily configurable import of flat files / database tables into SQL Server. Lastly, from a usability standpoint, There are many better methods to track Excel sheets or forms data (SharePoint, Excel 2013, Access, cloud/on premise drives) or using an internal WordPress distribution with some plugins like WP-document revisions.
As noted above I used Spock addition of dynamic lookup of values for the compare and value variable. Once I did that I added the hasExecuted flag.
Public Sub exportprojinfodata()
Dim stSQL As String
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConn As String
Dim iRowNo As Integer
Dim targetFieldNames As Variant
Dim rowData As Variant
Dim lastrow As Long
Dim sql As String
Dim i As Integer
Dim aField As String
Dim compare As Variant
Dim value As Variant
Dim hasExecuted As String
hasExecuted = False
With Sheets("Data2")
lastrow = .Range("A:A").Find(what:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
'Open a connection to SQL Server
conn.Open _
"Provider=SQLOLEDB;Data Source=PWIRTPAUDD1HV8;Initial Catalog=STAR;User Id=STAR_USER;Password=dcistarrtp"
'Skip the header row
iRowNo = 2
targetFieldNames = Join(WorksheetFunction.Transpose(wks_TargetFieldNames.Range("TargetFieldNames").value), "," & vbNewLine)
Do While iRowNo <= lastrow
rowData = wks_ProjDescription.Range("A" & iRowNo & ":AO" & iRowNo).value
compare = wks_ProjDescription.Range("B"& iRowNo).value
'Generate and execute sql statement to import the excel rows to SQL Server table
With rs
.ActiveConnection = conn
.Open "Select proj_id from dbo.STAR_DC_INITIAL_ProjectInfo_ExcelDevCopy where proj_id= " & compare
wks_ProjDescription.Range("AX2").CopyFromRecordset rs
.Close
End With
value = wks_ProjDescription.Range("AX"& iRowNo).value
If compare = value And hasExecuted = False Then
stSQL = "delete from dbo.STAR_DC_INITIAL_ProjectInfo_ExcelDevCopy where proj_id = " & value
conn.Execute stSQL
hasExecuted = True
End If
sql = "insert into dbo.STAR_DC_INITIAL_ProjectInfo_ExcelDevCopy ("
sql = sql & targetFieldNames
sql = sql & ") values (" & vbNewLine
'
'couldn't do transpose since rowData represents a row, not a column
For i = 1 To UBound(rowData, 2)
aField = Replace(rowData(1, i), "'", "''")
Select Case i
Case 1 To 40
sql = sql & "'" & aField & "', " & vbNewLine
Case 41
If aField Like "*,*" Then
sql = sql & "'" & """" & aField & """" & vbNewLine
Else
sql = sql & "'" & aField & "' " & vbNewLine
End If
End Select
Next i
sql = sql & ");"
' sql = sql & "');"
conn.Execute sql
iRowNo = iRowNo + 1
Loop
conn.Close
Set conn = Nothing
End With
End Sub
i'm a newbye I have a problem with the vba code to import data from a table in excel file access. Using Office 2010, but the launch of the code gives me an error:
(translate from Italian)
run-time error -2147217865 (80040e37) Microsoft Access Database engine cannot find object 'INCONTRI$A1:I108468.
Make sure the object exists and that its name and the path you typed BE CORRECTED.
HERE IS THE CODE:
VB:
Sub EXPORT2ACCESS()
Dim ultimariga As Long
Dim ultimacolonna As Integer
Dim foglio, finesel As String
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\TOTALBET\TOTALBET_XML_DB.accdb"
dbWb = Application.ActiveWorkbook.FullName
For i = 1 To 4
ultimariga = Sheets(i).Range("A" & Rows.Count).End(xlUp).Row
ultimacolonna = Sheets(i).Cells(1, Sheets(i).Columns.Count).End(xlToLeft).Column
finesel = Application.ConvertFormula("R" & ultimariga & "C" & ultimacolonna, xlR1C1, xlA1, toAbsolute:=xlRelative)
foglio = Application.Sheets(i).Name
Set cn = CreateObject("ADODB.Connection")
Dim cmd As ADODB.Command
dsh = "[" & Application.Sheets(i).Name & "$A1:" & finesel & "]"
cn.Open strCon
Set cmd = New ADODB.Command
cmd.CommandType = adCmdText
cmd.CommandText = "Delete * from " & foglio
cmd.ActiveConnection = cn.ConnectionString
cmd.Execute
With Sheets(i)
For x = 1 To ultimacolonna
campo = "[" & .Cells(1, x).Value & "]"
If x = 1 Then
stringa = campo
Else
stringa = stringa & ", " & campo
End If
Next x
End With
''Insert into a table called
strsql = "INSERT INTO " & foglio & "(" & stringa & ") "
strsql = strsql & "SELECT * FROM [Excel 12.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Debug.Print strsql
''Execute the statement
cn.Execute strsql
Next i
End Sub
the table "incontri" exists in my excel file and contain data. same sub worked for other sheets without problems and insert data in access table.
string that pass to exceute is:
VB:
INSERT INTO INCONTRI([Static_ID], [Stage_ID], [Season], [Number], [Data], [Time], [Status], [Venue_ID], [League]) SELECT * FROM [Excel 12.0;HDR=YES;DATABASE=C:\Users\Admin\Desktop\test xml.xlsm].[INCONTRI$A1:I108468]
Here is files (too big to put in forum, sorry:
Excel file with code and data: https://www.sugarsync.com/pf/D9350024_63096411_117675
Access file: https://www.sugarsync.com/pf/D9350024_63096411_117635
I'm going crazy to understand where the error is please help!
Thanks in advance to all the people who want to help me figure out where I'm wrong.
greetings
Vincent
You will probably find it easier to do this from Access. Access uses VBA like Excel, so you shouldn't have much trouble with it.
In Access, there's a command called DoCmd.TransferText. Click here for the full syntax.
Do a search for more examples. Good luck.