Excel VBA creating an ADO field_name variable
As you can see below in the code the " & tblName & " will work fine but instead of using the BankName (which the user cannot change because it is in the code) I would like to do the same as I did with the Table name and use a variable that gets its name from an excel spreadsheet rather that an actual name hard coded in a VBA module. I would like the variable field name entered in the Excel Spreadsheet by the user just like the table name is filled in by the user.
The problem is getting the ADO SQL string ( cmd.CommandText = "ALTER TABLE " & tblName & " Add Column BankName Char(25)" ) to recognize that the value in the Variable is the field name.
Sub AddFieldToAccess()
Dim cnn As ADODB.Connection
Dim cmd As ADODB.Command
Dim tblName as string 'User to input Table Name in cell C2
Dim fldName as string 'User to input Field Name in cell C3
tblName = ActiveSheet.Range("C2").Value 'Table Name
fldName = ActiveSheet.Range("C3").Value 'Field Name
'Open Access Database
Set cnn = New ADODB.Connection
With cnn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Open MyConn
End With
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = cnn
'create table
'I have already tried to use the same approach as the table Variable and no work
cmd.CommandText = "ALTER TABLE " & tblName & " Add Column " & fldName & " Char(25)"
cmd.Execute , , adCmdText
'If I do this I end up with a field named BankName
cmd.CommandText = "ALTER TABLE " & tblName & " Add Column BankName Char(25)"
cmd.Execute , , adCmdText
Set cmd = Nothing
Set cnn = Nothing
End Sub- Změněný typJohnTReed 23. června 2009 21:32I was told I was in the wrong forum
Odpovědi
- This forum is for SQL Data Services. You will have a better chance of getting a fast answer in one of the forums for SQL Server, VB, or Excel.
Aaron Stanley King - Microsoft Consultant - Perpetual Technologies, Inc. - http://www.perptech.com- Navržen jako odpověďAaron Stanley King 23. června 2009 20:59
- Označen jako odpověďJohnTReed 23. června 2009 21:46
Všechny reakce
- This forum is for SQL Data Services. You will have a better chance of getting a fast answer in one of the forums for SQL Server, VB, or Excel.
Aaron Stanley King - Microsoft Consultant - Perpetual Technologies, Inc. - http://www.perptech.com- Navržen jako odpověďAaron Stanley King 23. června 2009 20:59
- Označen jako odpověďJohnTReed 23. června 2009 21:46

