Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I would like to create and run a list of predefined queries on several similar databases.
The idea is open the database, run the queries, and then close.
Now I create each of them manually, run and then delete them from each database.
I don't know how to do it in VBA code.
Can anyone drop me a line on how to do it with a simple example?
You can use the Name property for each item in your database's QueryDefs collection to make a list of your saved queries. I think that addresses the title of your question. However the body of your question seems to ask for a lot more as far as I can tell.
You can load a string variable with the text from the SQL property of a QueryDef in your current database. Then use the OpenDatabase method to open another db file, and Execute that string there.
Public Sub RunQueryOnAnotherDb(ByVal pQuery As String, _
ByVal pRemoteDb As String)
Dim dbRemote As DAO.Database
Dim strSql As String
strSql = CurrentDb.QueryDefs(pQuery).SQL
'Debug.Print strSql
Set dbRemote = OpenDatabase(pRemoteDb)
dbRemote.Execute strSql, dbFailOnError
Debug.Print "RecordsAffected: " & dbRemote.RecordsAffected
dbRemote.Close
Set dbRemote = Nothing
End Sub
There's plenty of room to refine that one. You should add error handling for example. But, though quick & dirty, I hope it points you in a useful direction.
I tested it on my system like this, and it works with my db and query names.
Public Sub test_RunQueryOnAnotherDb()
Const cstrQuery As String = "qryTestDelete"
Const cstrRemoteDb As String = "C:\share\Access\0NewScratch.mdb"
RunQueryOnAnotherDb cstrQuery, cstrRemoteDb
End Sub
Related
I've been a reader on this site for years but today is the first day I have to ask my own question. Apologies if my formatting could be better.
I'm creating a tracking system for client applications and need to create a small notification indicating if the end user analyst is missing any checklist items regarding a given contact on the application.
My current set up involves a table with the contact information (RecordID, ParentID, FirstName, LastName, Email, Phone), a table with the analyst checklist (RecordID, ParentID, UniqueEmail, PhoneNumPresent, AddressIsResidential) and a form that contains a subreport that queries the correct contact names for the client.
The subreport is a list of record ID's, which are hidden from the end user but present to make the pop up checklist function, and the contact names. Ideally if any item is missing from the analyst checklist a small caution icon will pop up next to the contact name in the report and stay there until the checklist is completed. I can make this work in other parts of the form, for different checklists, but not inside of a report.
No matter which approach I try, the script changes the visibility of the icon on EVERY line item instead of just the line item in question. I have tried the approach below, as well as putting similar code into Detail_Format (Event doesn't trigger when I need it to), and storing the flag as a Yes/No Boolean on the same table that the report queries (the report does not update automatically and when it does update I run into the same issue).
Private Sub ContactFirstLastName_Click()
'Open Checklist for a given contact
CurrentContact = Me.ID
CurrentContactName = Me.ContactFirstLastName.Value
DoCmd.OpenForm "ContactsChecklistForm", , , , , acDialog
Dim rs As DAO.Recordset
SetRecord rs, "DocGatheringContacts", , Me.ID, "ID"
Dim UniqueEmail As Boolean
Dim PhoneNumPresent As Boolean
Dim DOBPresent As Boolean
Dim AddressResidential As Boolean
UniqueEmail = rs.Fields("UniqueEmail")
PhoneNumPresent = rs.Fields("PhoneNumPresent")
DOBPresent = rs.Fields("DOBPresent")
AddressResidential = rs.Fields("AddressResidential")
If UniqueEmail And PhoneNumPresent And DOBPresent And AddressResidential Then
Me.ContactWarning.Visible = False
Else
Me.ContactWarning.Visible = True
End If
End Sub
My confusion stems from the fact that in the above code Me.ID and Me.ContactFirstLastName.Value both accurately reflect the name that I click on, but after the analyst checklist ("ContactsChecklistForm") is closed Me.ContactWarning seems to affect all instances of "ContactWarning" instead of only the line instance I am clicking. From what I understand from Microsoft's documentation "Me" should be referring to the entire report the entire time, but it doesn't appear to be until Me.ContactWarning is used.
Any thoughts on why that may be happening or another approach I can take to achieve the desired effect?
I ended up taking a different approach to the problem. Initially I was attmepting to run my flagging script as part of the ContactFistLastName_click event so that it would trigger whenever the checklist was viewed, however I have found it more effective to run my flagging script as part of the checklist okay_click event so that it only triggers when the checklist is updated.
Drawing on the advice from June7 above, I switched from an image control to a textbox control that is linked to a field on the table that the report queries, and instead of using conditional formatting to either change the color or trigger a VBA function, I simply set the value of the field to either "" or the unicode character U+26A0 which is a warning symbol very similar to the image I was hoping to use.
The following script runs whenever the checklist is updated and causes a warning icon to be displayed or not to display as appropriate:
Private Sub OK_Click()
Dim rs As DAO.Recordset
SetRecord rs, "ApplicationContacts", , CurrentContact, "ID"
If UniqueEmail And PhoneNumPresent And DOBPresent And AddressResidential Then
rs.Edit
rs![ContactWarning] = ""
rs.Update
Else
rs.Edit
rs![ContactWarning] = ChrW(&H26A0)
rs.Update
End If
rs.Close
Set rs = Nothing
'Close checklist and save changes
DoCmd.Close
End Sub
Many thanks to June7 for getting me pointed in the right direction!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Dim cn As New MySql.Data.MySqlClient.MySqlConnection("server=...; User ID=...; password=...; database=...")
cn.Open()
Dim command As New MySqlCommand("select * from ...", cn)
Dim r As MySqlDataReader = command.ExecuteReader
While r.Read
Dim sb As StringBuilder = New StringBuilder()
While r.Read()
sb.AppendLine(r("messages"))
End While
TextBox2.Text = sb.ToString
End While
This code gets all messages from the MySQL table. How can i make it to only last(not read before) messages?
Supply to the code some kind of marker for where it left off. An incrementing identifier for the messages? A timestamp? It's your data, so it's your call. But basically, if you were to look at the data in the database manually, what value would you look for to determine "where you left off"? That's the value you want.
Then it's just a matter of putting that value into the WHERE clause. Something like this:
Dim command As New MySqlCommand("select * from SomeTable where MessageDate > #lastKnownDate", cn)
command.Parameters.Add(new MySqlParameter("#lastKnownDate", lastKnownDate))
// lastKnownDate would be the DateTime variable passed to this code.
// alternatively, use some other value as a "bookmark"
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
REAL PROBLEM: I am making a admin control panel for my mysql database. I just learned the most of the stuff in vb.net i know everything now learning query language and i run into this question. I want that there would be a user validator(detector) what i mean is lets say someone is creating an account and the username exist it would show a messagebox that the username already exist and cancel creating the account.
Here is my code:
Imports MySql.Data.MySqlClient
Public Class Deathlairregnu
Dim MySqlConn As MySqlConnection
Dim MySqlCmd As MySqlCommand
Private Sub ButtonNUS_Click(sender As Object, e As EventArgs) Handles ButtonNUS.Click
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString =
"server=localhost;userid=root;password=CONSORED;database=syscore"
Dim MySqlRea As MySqlDataReader
Try
MySqlConn.Open()
Dim Query As String
Query = "insert into syscore.normaluser (nusername,nemail,npass,nphone,ncity) values ('" & TextBoxNUsern.Text & "','" & TextBoxNEmail.Text & "','" & TextBoxNPass.Text & "','" & TextBoxNPhone.Text & "','" & TextBoxNCity.Text & "')"
MySqlCmd = New MySqlCommand(Query, MySqlConn)
MySqlRea = MySqlCmd.ExecuteReader
MessageBox.Show("Registration has been completed")
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
End Sub
End Class
OPTIONAL: Ok. I have another question maybe you can solve at the same time. How could i add guid generator when the register submit button is pressed if you know what i mean? i have it in my website asp.net that i made myself. Would be very nice and helpful.
Big thanks for those who will try to help me. I will check this topic every 5 minutes.
Adding a uniqueidentifier column and adding the default to generate new guid
Downvotes probably because you didn't paste your code here, plus the fact that the question has been asked and answered many times. Did you search before asking?
I did the important part. Optional is not needed for me but would've been good. Here: https://www.youtube.com/watch?v=ovoVfHW3Q8Y.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am required to provide a way for users to choose which column they want to display from a table. The user has a combo box of column names in a form which they can select one of and then hit a button which opens a report. I wrote some code which creates an SQL query based on the user's input, but it's not being called. I've tried inserting MsgBox statements, asserts, etc., but it never gets called. If I use a macro instead, that will be run, but not this sub...
Private Sub Report_Open(Cancel As Integer)
Dim field As String
Dim sqlQuery As String
Dim ctl As Control
ctl = "Forms![RuleGroupForm]![selectRuleFieldCombo]"
field = "rules.[" & ctl & "]"
' E.g. if the field was "Source File", the final query should look like this:
'SELECT overview.ID, relationship.rulesID, rules.[Source File], overview.[Rule Group], rules.RulegroupID
'FROM (overview INNER JOIN relationship ON overview.id=relationship.id)
'INNER JOIN rules ON relationship.rulesID=rules.ID
'WHERE rules.[Source File] IS NOT NULL;
sqlQuery = "SELECT overview.ID, relationship.rulesID, " & field
sqlQuery = sqlQuery & ", overview.[Rule Group], rules.RulegroupID"
sqlQuery = sqlQuery & "FROM (overview INNER JOIN relationship ON overview.id=relationship.id) "
sqlQuery = sqlQuery & "INNER JOIN rules ON relationship.rulesID=rules.ID"
sqlQuery = sqlQuery & "WHERE " & field & " IS NOT NULL;"
Me.RecordSource = sqlQuery
Requery
debugText = "New SQL Query = " & sqlQuery
End Sub
Thanks.
Edit: Resolved, not sure how to respond to own question...
There are a few things to check, apart from close and open, when you get odd behaviour such as this in Access. One is to see if the event on the properties sheet for the form or report, Open in this case, still contains [Event Procedure] - occasionally a form or report can have the code, but the event is not marked. When developing, that is, adding forms, reports and code, it is a good idea to run Compact and Repair on a regular basis, this also means regular back-ups - a simple copy saves a lot of grief. Finally, when developing fairly regular Decompiles are a good idea. I keep a small script that I can drop the Access file on to run decompile.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I want to compare two ms-access .mdb files to check that the data they contain is same in both.
How can I do this?
I've done this kind of thing in code many, many times, mostly in cases where a local MDB needed to have updates applied to it drawn from data entered on a website. In one case the website was driven by an MDB, in others, it was a MySQL database. For the MDB, we just downloaded it, for MySQL, we ran scripts on the website to export and FTP text files.
Now, the main point is that we wanted to compare data in the local MDB to the data downloaded from the website and update the local MDB to reflect changes made on the website (no, it wasn't possible to use a single data source -- it was the first thing I suggested, but it wasn't feasible).
Let's call MDB A your local database, and MDB B the one you're downloading for comparison. What you have to check for is:
records that exist in MDB A but not in MDB B. These may or may not be candidates for deletion (this will depend on your particular data).
records that exist in MDB B but not in MDB A. These you will append from MDB B to MDB A.
records that exist in both, which will need to be compared field by field.
Steps #1 and #2 are fairly easily accomplished with queries that use an outer join to find the missing records. Step 3 requires some code.
The principle behind the code is that the structure of all the tables in both MDBs are identical. So, you use DAO to walk the TableDefs collection, open a recordset, and walk the fields collection to run a SQL statement on each column of each table that either updates the data or outputs a list of the differences.
The basic structure behind the code is:
Set rs = db.OpenRecordset("[SQL statement with the fields you want compared]")
For Each fld In rs.Fields
' Write a SQL string to update all the records in this column
' where the data doesn't match
strSQL = "[constructed SQL here]"
db.Execute strSQL, dbFailOnError
Next fld
Now, the major complexity here is that your WHERE clause for each field has to be different -- text fields need to be treated differently from numeric and data fields. So you'll probably want a SELECT CASE that writes your WHERE clause based on the field type:
Select Case fld.Type
Case dbText, dbMemo
Case Else
End Select
You'll want to use Nz() to compare the text fields, but you'd use Nz(TextField,'') for that, while using Nz(NumericField,0) for numeric fields or date fields.
My example code doesn't actually use the structure above to define the WHERE clause because it's limited to fields that work very well comparing concatenated with a ZLS (text fields). What's below is pretty complicated to read through, but it's basically an expansion on the above structure.
It was written for efficiency of updates, since it executes a SQL UPDATE for each field of the table, which is much more efficient than executing a SQL UPDATE for each row. If, on the other hand, you don't want to do an update, but want a list of the differences, you might treat the whole thing differently. But that gets pretty complicated depending on the output,
If all you want to know is if two MDBs are identical, you would first check the number of records in each table first, and if you have one non-match, you quit and tell the user that the MDBs aren't the same. If the recordcounts are the same, then you have to check field by field, which I believe is best accomplished with column-by-column SQL written dynamically -- as soon as one of the resulting SQL SELECTS returns 1 or more records, you abort and tell your user that the MDBs are not identical.
The complicated part is if you want to record the differences and inform the user, but going into that would make this already-interminable post even longer!
What follows is just a portion of code from a larger subroutine which updates the saved query qdfOldMembers (from MDB A) with data from qdfNewMembers (from MDB B). The first argument, strSQL, is a SELECT statement that is limited to the fields you want to compare, while strTmpDB is the path/filename of the other MDB (MDB B in our example). The code assumes that strTmpDB has qdfNewMembers and qdfOldMembers already created (the original code writes the saved QueryDef on the fly). It could just as easily be direct table names (the only reason I use a saved query is because the fieldnames don't match exactly between the two MDBs it was written for).
Public Sub ImportMembers(strSQL As String, strTmpDB As String)
Const STR_QUOTE = """"
Dim db As Database
Dim rsSource As Recordset '
Dim fld As Field
Dim strUpdateField As String
Dim strZLS As String
Dim strSet As String
Dim strWhere As String
' EXTENSIVE CODE LEFT OUT HERE
Set db = Application.DBEngine(0).OpenDatabase(strTmpDB)
' UPDATE EXISTING RECORDS
Set rsSource = db.OpenRecordset(strSQL)
strSQL = "UPDATE qdfNewMembers INNER JOIN qdfOldMembers ON "
strSQL = strSQL & "qdfNewMembers.EntityID = qdfOldMembers.EntityID IN '" _
& strTmpDB & "'"
If rsSource.RecordCount <> 0 Then
For Each fld In rsSource.Fields
strUpdateField = fld.Name
'Debug.Print strUpdateField
If InStr(strUpdateField, "ID") = 0 Then
If fld.Type = dbText Then
strZLS = " & ''"
Else
strZLS = vbNullString
End If
strSet = " SET qdfOldMembers." & strUpdateField _
& " = varZLStoNull(qdfNewMembers." & strUpdateField & ")"
strWhere = " WHERE " & "qdfOldMembers." & strUpdateField & strZLS _
& "<>" & "qdfNewMembers." & strUpdateField & strZLS _
& " OR (IsNull(qdfOldMembers." & strUpdateField _
& ")<>IsNull(varZLStoNull(qdfNewMembers." _
& strUpdateField & ")));"
db.Execute strSQL & strSet & strWhere, dbFailOnError
'Debug.Print strSQL & strSet & strWhere
End If
Next fld
End If
End Sub
Code for function varZLSToNull():
Public Function varZLStoNull(varInput As Variant) As Variant
If Len(varInput) = 0 Then
varZLStoNull = Null
Else
varZLStoNull = varInput
End If
End Function
I don't know if that's too complex to make sense, but maybe it will help somebody.
You can try AccessDiff (paid product). It has the ability to compare the schema, the data, and also access objects. It has a GUI and also a command line interface.
Disclosure: I am the creator of this tool.
Take text dumps of database tables and simply compare the dumped text files using BeyondCompare (or any other text comparison tool). Crude but can work!
I have very good experience with Cross-Database Comparator. It is able to compare structure and/or data.
See the Compare Access databases section at the Microsoft Access third party utilities, products, tools, modules, etc. page at my website.
I've added "table diff" feature to my accdbmerge utility not so long time ago.
I beleive that this answer will not help to solve original question, but it may be helpful for someone faced with the same problem in the future.
If you want to know if the files are identical then
fc file1.mdb file2.mdb
on a DOS command line.
If the files aren't identical but you suspect they contain the same tables and records then the easiest way would be quickly write a small utility that opens both databases and cycles through the tables of both performing a heterogeneous query to extract the Diff between the two files.
There are some tools out there which will do this for you, but they all appear to be shareware.