문제

I am trying to insert a new row, populated with data, into a simple Access Table using SQL from Excel VBA and can't get over the first hurdle.

I have a single Table called "Test" with four fields;

  • ID [an AutoNumber field identified as the Primary Key]

  • Text1 [A text field]

  • YN1 [A Yes/No field]

  • No1 [A Long Integer numeric field]

There are no relationships or no indexes set other than in the AutoNumber field (PK). All fields have 'Required' set to No, no validations set and no defaults set. Text1 can accept zero length.

The business end of my VBA code is as follows:

'Connection string.
    stcnt = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & stDBPath & stDBname

'Instantiate the ADO-objects
    Set cnt = New ADODB.Connection

'Open the connection for first Query
    With cnt
        .Open (stcnt) 'Open the connection.
        .CursorLocation = adUseClient 

'Test Data
T1 = "ABC123"
Y1 = -1
N1 = 17

        stSQL1 = "INSERT INTO Test(Text1, YN1, No1) " _
                & "VALUES(T1, Y1, N1)"

        .Execute (stSQL1)

    End With

    'Close connection
    cnt.Close

My variables have been Dimmed appropriately (Y1 as Boolean) and the path/database names declared correctly.

At the line

 .Execute (stSQL1)

I am getting an error "No value given for one or more required parameters"

I have read that you can omit the AutoNumber field and its value (which I have done). If not, could someone please give me the syntax to include this. With my limited knowledge/research I may also not be treating the ‘YesNo’ field properly. Again any advice and syntax to deal with this would be gratefully received.

The Access database is sitting on my hard drive and I get the same error irrespective of whether Access is open or closed when running the VBA code.

My SQL statement pasted directly into the Access ‘SQL View’ window runs fine and inserts a correctly populated row in the Table Test.

Any help from an expert (especially with correct syntax) to get me over this one would be much appreciated please.

도움이 되었습니까?

해결책

Because stSQL1 is a string, the compiler doesn't see that you want variables T1, Y1 and No1 to be inserted into the string. You need to build the string yourself:

stSQL1 = "INSERT INTO Test(Text1, YN1, No1) " _
                & "VALUES('" & T1 & "'," & Y1 & "," & N1 & ")"

You need to place a single quote around the text value.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top