dageci
New Member
- Joined
- Mar 10, 2016
- Messages
- 16
Hello,
Let's say we have a worksheet called: Sales
In this worksheet, we have 2 columns: Product, Price
We want to insert into this worksheet from VBA using an SQL INSERT 1 record where the Product is "Computers" and the Price is 30.
If we do this when we have some records it is ok, but when we only have the first row that contains the column names (blank worksheet), the Price is getting an apostrophe and it is inserted as an text.
How to solve this?
Here is the sample code:
Let's say we have a worksheet called: Sales
In this worksheet, we have 2 columns: Product, Price
We want to insert into this worksheet from VBA using an SQL INSERT 1 record where the Product is "Computers" and the Price is 30.
If we do this when we have some records it is ok, but when we only have the first row that contains the column names (blank worksheet), the Price is getting an apostrophe and it is inserted as an text.
How to solve this?
Here is the sample code:
Code:
Private Sub CommandButton1_Click()
Dim Connection As ADODB.Connection
Dim ConnectionString As String
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & _
"Extended Properties=Excel 8.0;"
Dim SQL As String
' worksheet Sales columns: Product, Price
SQL = "INSERT INTO [Sales$] VALUES('Computers', 30)"
Set Connection = New ADODB.Connection
Call Connection.Open(ConnectionString)
Call Connection.Execute(SQL, , CommandTypeEnum.adCmdText Or ExecuteOptionEnum.adExecuteNoRecords)
Connection.Close
Set Connection = Nothing
End Sub