-4

I have a field called Product_Id(type string), which has length of 7 and starting with 0. But while inserting through VBA into a table field of type text the zeros is not getting inserted.

This is the insert query:

dbs.Execute "INSERT INTO tablename (PROD_NBR)VALUES (" & prodID & ");"  
Olle Sjögren
  • 5,315
  • 3
  • 31
  • 51
Cherry
  • 393
  • 1
  • 4
  • 15

2 Answers2

5

I think I have fixed the error - you need to declare the value in single quotes.

The PROD_NBR is a string type and field in the table is text type, then the inserting variable should be declared inside single quotes then double quotes and between two & symbols:

dbs.Execute "INSERT INTO tablename (PROD_NBR)VALUES ('" & prodID & "');" 
Olle Sjögren
  • 5,315
  • 3
  • 31
  • 51
Cherry
  • 393
  • 1
  • 4
  • 15
0

Responding to @Cherry's answer, the following method is less tedious than a parameterized query, aka prepared statement. prodID can safely contain quotes and other special characters.

    With dbs.OpenRecordset("tablename")
        .AddNew
        .Fields("PROD_NBR") = prodID
        .Update
    End With

Regarding the "starting with zero" part of your question, do you want PROD_NBR to always be 7 characters, padded with leading 0's? Then replace prodID with:

    Right("0000000" & prodID, 7)
Tom Robinson
  • 1,850
  • 1
  • 15
  • 14