Search code examples
vbams-accesstypessubroutinefunction-parameter

Passing a table as a parameter to a function


I am trying to simply pass a table or table name to a function to use in a query. The problem is I don't know what datatype to use for an entire table.

My code looks something like this

querytable MyTable, SomethingElse

Sub querytable(table As String, string As String)

   query1 = "insert into " & table & "(TABLEFIELD) values (" & string & ")"
   DoCmd.RunSQL query1

End Sub

This is not working for me and any help would be greatly appreciated.


Solution

  • For what you're trying to do here you need to pass the table name as a string.

    Your code doesn't follow quite a number of common conventions, including avoiding the use of reserved words in your code.

    Try to make sure you declare all your variables before using them. Use Option Explicit at the top of all of your modules. And always declare your variables with a data type other than variant.

    You might try code that looks something like this:

    Call InsertInto sTableName, sData
    'or
    'Call InsertInto "ActualTableName", "SomeValue"
    
    Public Sub InsertInto(ByVal sTable As String, ByVal sValue As String)
        Dim sSQL as String
        sSQL = "INSERT INTO " & sTable & "(CompanyName) VALUES (" & sValue & ")"
        Debug.Print sSQL
        CurrentDb.Execute sSQL, dbFailOnError
    End Sub