I have a form with an unbound combobox that has all the column headings for the table dbo_orderheader. What I want to do is use the combobox field to act as the table column header instead of hard coding it to a specific table column header, that way a user can search dynamically from the form on the column they choose instead of having a huge list of search boxes for each table column.
Please can anyone help on a way to do this in an access query? I am using Access 2007.
Thanks.
See Picture Attached
I'm pretty sure that there's no way to imbed a form reference as a column heading in a static query design, but you could use code behind your form to dynamically update the query design and then open the query, something like this
Private Sub btnOpenQuery_Click()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Const queryName = "flexQuery"
Set cdb = CurrentDb
DoCmd.Close acQuery, queryName, acSaveNo
On Error Resume Next
DoCmd.DeleteObject acQuery, queryName
On Error GoTo 0
Set qdf = cdb.CreateQueryDef(queryName, _
"SELECT URN, StyleNo, [" & Me.Combo3.Value & "] " & _
"FROM dbo_OrderHeader " & _
"WHERE [" & Me.Combo3.Value & "]=""" & Me.Text5.Value & """" _
)
Set qdf = Nothing
Set cdb = Nothing
DoCmd.OpenQuery queryName, acViewNormal
End Sub
Note: This sample code assumes that the "dynamic" column is a Text column, so it puts " characters around the Text5.Value when constructing the SQL statement. This code would have to be enhanced to handle other column types (e.g., no quotes for numeric columns, and perhaps # delimiters for dates).
Related
I'm trying to use Access's upsizing wizard to move the data from Access to SQL Server. I'm currently on this error but can't figure out where the property is coming from;
Property 'Attributes' already exists for 'table'.
The SQL its trying to run is;
EXEC sp_addextendedproperty N'Attributes', N'2', N'user', N'dbo', N'table', N'table', N'column', N'ID'
But the table in Access doesn't include an ID column and I can't see anything in the properties on the table to indicate why it's trying to add the property for SQL Server.
In the wizard guide I chose not to import any extras like indexes, triggers etc.
Any ideas why the wizard is doing this and how to stop it trying to create the properties?
Alternatively, are there any other tools which would moved the data from Access to MSSQL while keeping Access front-end objects in place and working?
The upsizing wizard had its deficiencies from the start, and has been removed from recent versions of Access. I recommend not using it.
Personally, I have a form that handles upsizing for me. It's a form with on it two text boxes named ConStr and adoString (the first containing the connection string for Access to use including the ODBC; prefix, the second containing either an ODBC or OLEDB string for ADO to use), a button named ToSQL, and a listbox named lstTables. It contains the following code:
To populate the local tables on load:
Private Sub Form_Load()
lstTables.RowSourceType = "Value List"
Dim iterator As Variant
For Each iterator In CurrentDb.TableDefs
If Not iterator.NAME Like "MSys*" And Not iterator.NAME Like "~*" Then
lstTables.AddItem iterator.NAME
End If
Next iterator
End Sub
To move the tables over to SQL server:
Private Sub ToSQL_Click()
Dim i1 As Variant
Dim td As DAO.TableDef
Dim NewTd As DAO.TableDef
Dim db As DAO.Database
Set db = CurrentDb
'Iterate through all selected tables
With lstTables
For Each i1 In .ItemsSelected
Set td = db.TableDefs(.ItemData(i1))
'Add a primary key if none exist
'AddPK td 'Not providing this one as it's not part of normal upscaling
'Move the table to SQL server
DoCmd.TransferDatabase acExport, "ODBC Database", _
conStr _
, acTable, .ItemData(i1), .ItemData(i1)
'Rename the local table to name_local
td.NAME = .ItemData(i1) & "_local"
'Change the remote table to the schema specified
'ADOChangeSchema GetDefaultSchema(), "mySchema", .ItemData(i1) 'Not providing this one as it's not part of normal upscaling
'Set the primary key in SQL server
ADOAddPrimaryKey GetDefaultSchema(), .ItemData(i1), GetPKName(td)
'Create a new linked table, linking to the remote table
Set NewTd = db.CreateTableDef(.ItemData(i1), 0, GetDefaultSchema() & .ItemData(i1), conStr)
db.TableDefs.Append NewTd
Next i1
End With
End Sub
And some helper functions:
Public Sub ADOAddPrimaryKey(SchemaName As String, tableName As String, FieldName As String)
On Error GoTo SetNotNull
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
conn.Open adoString
cmd.ActiveConnection = conn
cmd.CommandText = "ALTER TABLE " & SchemaName & ".[" & tableName & "] ADD CONSTRAINT [" & tableName & "_PK] PRIMARY KEY CLUSTERED([" & FieldName & "]);"
cmd.Execute
Exit Sub
SetNotNull:
If Err.Number = -2147217900 Then
cmd.CommandText = "ALTER TABLE " & SchemaName & ".[" & tableName & "] ALTER COLUMN [" & FieldName & "] INTEGER NOT NULL"
cmd.Execute
cmd.CommandText = "ALTER TABLE " & SchemaName & ".[" & tableName & "] ADD CONSTRAINT [" & tableName & "_PK] PRIMARY KEY CLUSTERED([" & FieldName & "]);"
cmd.Execute
Else
Err.Raise Err.Number
End If
End Sub
Public Function GetDefaultSchema() As String
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
conn.Open adoString
Set rs = conn.Execute("SELECT SCHEMA_NAME()")
GetDefaultSchema = rs.Fields(0)
End Function
Public Function GetPKName(td As DAO.TableDef) As String
'Returns the name of the first field included in the primary key (WARNING! Doesn't return all fields for composite primary keys!)
Dim idx As DAO.Index
For Each idx In td.Indexes
If idx.Primary Then
GetPKName = idx.Fields(0).NAME
Exit Function
End If
Next idx
End Function
This form only preserves data and the primary key, and makes several assumptions (too lazy to avoid them), such as: table names don't contain square brackets, there are no composite primary keys, the table schema is safe for use in SQL statements, there are no attachment fields or multivalued fields, and there are no relationships (had a version that preserved relationships, but... I honestly don't know where it is now).
It also leaves a renamed copy of the local table. The original version then tests 1K random rows to check if the content is identical, but I've omitted that for brevity.
You can use this as a starting point, since it might need tuning to suit your specific needs.
I am trying to print a separate pdf file (billing invoice) from a form for each record in my database.
Form to print: BillingInvoice-
Source for form: FamilySubDIscSubDIscGrand
Primary field: Fnum
I've tried taking code from here:
How to output multiple PDF files based on record in MS Access?
This is the code that code as I have tried to modify it:
Option Compare Database
Option Explicit
Private Sub PrintBtn01_Click()
Dim rsGroup As DAO.Recordset
Dim ColumnName As String, myPath As String
myPath = "C:\test\"
Set rsGroup = CurrentDb.OpenRecordset("SELECT DISTINCT FNum FROM FamilySubDIscSubDIscGrand", _
dbOpenDynaset)
Do Until rsGroup.EOF
ColumnName = rsGroup!FNum
' OPEN FORM, FILTERING RECORDSOURCE BY COLUMN VALUE
DoCmd.OpenForm "BillingInvoice-", acViewPreview, , "Column='" & ColumnName & "'"
' OUTPUT FORM TO FILE
DoCmd.OutputTo acOutputForm, "BillingInvoice-", acFormatPDF, _
myPath & ColumnName & ".pdf", False
rsGroup.MoveNext
Loop
End Sub
I’m doing something wrong.
It is successfully saving the pdf’s with the FNums in sequence, but printing the individual records for each FNum, it is printing all the records. So I end up with:
FNum001.pdf (all records for db)
FNum002.pdf (all records for db)
Fnum003.pdf (all records or db)
...
But what I need is:
FNum001.pdf (individual record for FNum001)
FNum002.pdf (individual record for FNum002)
FNum003.pdf (individual record for FNum003)
...
If FNum is numerical, you should not surround the criteria value with single quotes, i.e. this:
"Column='" & ColumnName & "'"
Should become:
"Column=" & ColumnName
Also, unless you have a field on your form called Column, this should be changed to:
"FNum = " & ColumnName
I want to populate a List Box on a Word User Form based on the data entered in a Text Box on the same form. Ideally this would happen in real time (using the change event I think) with each character entered in the Text Box filtering the items that appear in the List Box.
The data source is an Excel "data base" accessed using DAO. The code below works but it enters the entire data base into List Box (based on this - Link).
Private Sub UserForm_Initialize()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim NoOfRecords As Long
'Open the database (Excel File)
Set db = OpenDatabase("C:\Users\T400\Documents\UserFormListTest.xlsx" _
, False, False, "Excel 8.0")
'Retrieve the recordset > Excel Range = "ListBoxData"
Set rs = db.OpenRecordset("SELECT * FROM ListBoxData")
' Determine the number of retrieved records
With rs
.MoveLast
NoOfRecords = .RecordCount
.MoveFirst
End With
' Set the number of Columns = number of Fields in recordset
ListBox1.ColumnCount = rs.Fields.Count
ListBox1.Column = rs.GetRows(NoOfRecords)
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Sub
How can I filter the data so the List Box is only populated per the Text Box? I was hoping for a simple solution like maybe modifying the SELECT * query portion of the code.
Is this possible? Or is there a better way?
As i mentioned in the comment to the question, MS Excel uses Jet database engine. So, you have to use wildcards which correspond to that database engine.
So, if you want to develop custom "search/find" functionality, you may add Combobox control on the form with these options: All, StartsWith, Contains and EndsWith. A sample code should look like (replace the name of controls to yours):
Dim sName As String
Dim sSearchType As String
Dim sQry As String
sName = TextBox1.Text
sSearchType = ComboBox1.Value
sQry = "SELECT * FROM ListBoxData "
Select Case sSearchType
Case "All"
'do nothing; return all records
Case "StartsWith"
sQry = sQry & "WHERE Name Like '" & sName & "*'"
Case "Contains"
sQry = sQry & "WHERE Name Like '*" & sName & "*'"
Case "EndWith"
sQry = sQry & "WHERE Name Like '*" & sName & "'"
End Select
Set rs = db.OpenRecordset(sQry)
'other stuff
More about wildcards, you'll find here:
Access wildcard character reference
Office: Wildcard Characters used in String Comparisons
Im trying to pull some information from out helpdesk system into the subject line of an email. the helpdesk system is MSSQL based
My goal is to have a form with a multi column ComboBox that inserts the results of the SQL query into a multi column combobox respectively.
I was planning to use the selected value in the combo box to insert into the subject line of an email, with some text manipulation. but I have not get that far yet :)
This code gives me the query in the combobox however the data is in two separate rows, where I would like them in the same row
can anyone tell me what I am doing wrong?
Private Sub userform_initialize()
UserForm1.ComboBox1.ColumnCount = 2
On Error GoTo UserForm_Initialize_Err
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
cnn.Open "Provider=SQLOLEDB;Data Source=sqlserver;" & _
"Initial Catalog=databasename;" & _
"Integrated Security=SSPI;"
rst.Open "Select field1, field2 from table", _
cnn, adOpenStatic
rst.MoveFirst
With UserForm1.ComboBox1
.Clear
Do
.AddItem rst.Fields(0)
.AddItem rst.Fields(1)
rst.MoveNext
Loop Until rst.EOF
End With
UserForm_Initialize_Exit:
On Error Resume Next
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
Exit Sub
UserForm_Initialize_Err:
MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
Resume UserForm_Initialize_Exit
You are twice adding an item to the combobox (one for each field), so of course you get separate rows. If you first put the results in a two dimensional array (arr(rowcount, 1) ) and then set the items property of the combobox to the array it should have two columns (you still may have to set the properties of the combobox to show both columns though)
This has taken me nearly 2 weeks and I don't know what else to do. I have a main form (UserSearch) that has a subform (TestUserSub). The associated table for both forms is tblusers.
very simple; on the main form (UserSearch) I have a ComboBox associated with the fields in the tblusers eg cmbid, cmbname, cmbdept and so on. All I want, is for a user to make a selection from any of these comboboxes and for the associated fields to display in the subform (TestUserSub). I have tried several different versions of code in the after update event in a couple of the ComboBoxes and nothing is happening in the subform or in other instances I get error message.
One example i have tried is filtering running an SQL command
Private Sub cmbid_AfterUpdate()
Dim strSQL As String
If IsNull(Me.cmbaccess) Then
Me.RecordSource = "tblusers"
Else
strSQL = "SELECT tblUsers.[Team Member_ID] FROM tblUsers " & _
"WHERE (((tblUsers.[Team Member_ID])= " & [form_testusersub].[txtid2]))& ";"
Me.RecordSource = strSQL
End If
End Sub
The above didn't work... Can someone please help me with this. I have a sample database that I have been working off of and by some very strange way, they have managed to do this same thing without calling any code. Is this possible?
I was able to figure out the code using the sample below
Private Sub yourcombobox_AfterUpdate()
Dim LSQL As String
If IsNull(Me.yourcombobox.Value) Then
Form_yoursubform.RecordSource = "tablename"
Me.yoursubform.Requery
requerysubform 'macro to requery the whole form
Else
LSQL = "select * from tablename"
LSQL = LSQL & " where field= '" & yourcombobox & "'"
Form_yoursubform.RecordSource = LSQL
requerysubform 'macro to requery the whole form
End If
End Sub
hope this helps.