0

Sorry for my dumb question. I programming in Access (VBA) and I’m trying to send a variable called machine into a sql code and then insert it into a table. But i have no idea how to do it. this is my code for so far:

Private Sub MachineToevoegen_Click()
        Dim SQL As String
        Dim Machine As String
        Machine = Machine_keuze
        SQL = "INSERT INTO Machines ([Machine]) VALUES(Machine)"
        DoCmd.RunSQL SQL
    End Sub

If someone could help me with this it would be great.

2
  • Error message (if not add Option Explicit)? Read on vba set string variable! Read Bobby Tables to understand why you should not concat sql strings, but use params! Commented Sep 11, 2020 at 10:42
  • You don't assign a string to Machine. See me edit below. Commented Sep 11, 2020 at 11:28

2 Answers 2

2

Create a query where you pass the Machine as parameter.

For example:

PARAMETERS [prmMachine] Text (255);
INSERT INTO Machines ([Machine])
SELECT [prmMachine] AS _Machine;

Then, call the query in VBA:

With CurrentDb().QueryDefs("YourQueryName")
    .Parameters("[prmMachine]").Value = Machine_keuze 
    .Execute dbFailOnError
End With
Sign up to request clarification or add additional context in comments.

Comments

0

Try below.

Private Sub MachineToevoegen_Click()

    Dim SQL As String
    Dim Machine As String

    Machine = "Machine_keuze"
    SQL = "INSERT INTO Machines ([Machine]) VALUES('" & Machine & "')"
    DoCmd.RunSQL SQL

End Sub

4 Comments

Don't show unexperienced users how to concat sql strings as they will get bitten by injections! And look at the string ;(
@ComputerVersteher I aggreed but its really hard for beginners to catch advanced queries.
Harder than catching why does "INSERT INTO Machines ([Machine]) VALUES('" & "Machinename containg'Quote" & "')" (e.g "O'neil capacitor") fail?
Saying it's hard is nonsense. Just use a tempvar: TempVars!Machine = "Machine_keuze", and SQL = "INSERT INTO Machines ([Machine]) SELECT TempVars!Machine". 0 added lines, avoids issues with string delimiters so conceptually likely more simple for beginners

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.