I want to make the created table name unique, possibly by using hh:mm:ss in the table name so that if the macro is played time after time, it won't be telling me "table name already exists".
There are two parts to the query. One for creating the table, and one for refreshing access data objects so that the new table becomes visible.
Sub SelectIntoX()
Dim dbs As Database
Set dbs = CurrentDb
' Part 1 Select all records in the scheme table
' and copy them into a new table
dbs.Execute "SELECT * INTO " _
& Format(Date, "yymmdd") & "_Scheme" & " FROM dbo_scheme;"
'Part 2 refresh Access data objects to see new table appear
DBEngine(0)(0).TableDefs.Refresh
DoCmd.SelectObject acTable, Format(Date, "yymmdd") & "_Scheme", True
End Sub
The problem I have is that yymmdd is not unique and I am running it a lot each day.
I have also tried this hhmmss, but it only adds on zeroes.
This should be a good alternative:
Format(Now(), "yyyymmddhhmmss")
Related
I have a unique index of fields in my table in microsoft access. The fields are Shift, Operator, Date_Field, and Machine. I have a data entry form with combobox selections for these fields, except for the date which autopopulates today's date. I want to be able to navigate the form te the record that matches the existing Shift/Operator/Date/Machine combo if it already exists. I have a DLookup function that checks to see if such a record exists already, but now I need to know how to change the form so it is entering the data on that record instead of a new one.
Here's what I have so far. It is being activated in the AfterUdate of one of the last combobox in the tab order.
Dim int_ID As Integer
With Me
'checks if duplicate record exists and stores it as int_ID variable
int_ID = Nz(DLookup("ID", "Tracking", "Shift= " & Val(.ShiftCbo) & " And Operator='" & .OpCbo.Column(1) & "' And Date_Field=#" & .DateBox & "# And Machine='" & .MachineCbo.Column(1) & "'"), 0)
End With
If int_ID <> 0 Then
'I need to know what to put here to take the form to the existing record.
End If
I've tried to use Cmd.GoToRecord but that doesn't work.
One of my favorite (and simplest) methods is using Me.Recordsource
Once you have your code working correctly which defines the filter criteria, try something like this:
Me.Recordsource= "select * from UnderlyingFormMainQuery where TextColumnName='" & varString & "' or NumericColumnName=" & intSomething
Me.Requery
I am creating a form in an Access database that allows a user to import an Excel workbook into the database, then inserts a column with that day's date as a way to log when the record was imported, with the idea that I can later compare this to a master database and update accordingly.
My code is below:
Private Sub btnImport_Click()
'create a new file system object that will check for conditions and import the file as a new table if a valid name is chosen
Dim FSO As New FileSystemObject
Dim strSQL As String
'Dim curDatabase As Object
Dim tableTest As Object
Dim fieldNew As Object
Dim todayDate As Date
Dim tempTable As String
tempTable = "TempTable" & CStr(Date)
'MsgBox TempTable
'If no file name in box
If Nz(Me.txtFileName, "") = "" Then
MsgBox "Please choose a file."
Exit Sub
End If
'If a file name is in box and the file can be located
If FSO.FileExists(Me.txtFileName) Then
fileImport.ImportExcel Me.txtFileName, tempTable
'once it imports the table, it then adds today's date (the upload date)
todayDate = Date
strSQL = "INSERT INTO tempTable (Upload_Date) Values (#" & Date & "#);"
DoCmd.RunSQL strSQL
'DoCmd.RunSQL ("DROP Table TempTable")
Else
'Error message if file can't be found
MsgBox "File not found."
End If
End Sub
Unfortunately, right now I am getting two problems.
The first is
run-time error 3127: The INSERT INTO statement contains an unknown
field name.
I thought I wanted to insert a new field, so I'm a little perplexed by this error.
I'm also getting another error; the compiler doesn't seem to like when I use tempTable for the table name. I'm trying to use a reference to the table name, rather than the actual name of the table itself, because this will end up being a daily upload, so the name of the table that is having this column inserted into it will change every day.
I appreciate any guidance that you can give; I'm fairly new to VBA.
UPDATE: I ended up solving this issue by A. using an UPDATE statement and using CurrentDb.Execute to add the date. I found that this worked for me:
strSQL = "ALTER TABLE TempTable ADD COLUMN Upload_Date DATE;"
strSQL2 = "UPDATE TempTable SET Upload_Date = '" & Date & "'"
DoCmd.RunSQL strSQL
CurrentDb.Execute strSQL2
INSERT INTO doesn't add columns, it just adds rows (with data in existing columns). Look into ALTER TABLE ( https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/alter-table-statement-microsoft-access-sql )
I'm not sure if it's related, but the table name you use in strSQL is "tempTable", yet the table name you pass to fileImport.ImportExcel is "TempTable" (i.e. the capitalization of the first letter is inconsistent).
If the variable "tempTable" is meant to hold the name of the table (so it can be used for different table names) then it should be outside of the SQL strings:
strSQL= "ALTER TABLE " & tempTable " & " ADD COLUMN Upload_Date DATE;"
strSQL2 = "UPDATE " & tempTable & " SET Upload_Date = '" & Date & "';"
Otherwise you are amending and updating a table called "TempTable" rather than inserting the calculated table name from the variable into the SQL string.
Also note that there should be a semi-colon at the end of strSQL2 as well.
I am trying to set a quantity value based on a sum of the current quantity and then subtracting an amount based on a quantity value in another table.
My current thought process is: If QuantityA is less than or equal to Quantity B then subtract QuantityA from Quantity B.
I am no expert on SQL and MS VBA, so I was wondering how I can make an if statement with the two different tables.
Private Sub Command23_Click()
If QuantityA <= QuantityB Then
QuantityB = QuantityB - QuantityA
Else
MsgBox "You can not hire that many" & ToolName & "as there is only" & [DEPARTMENT TOOLS (stocked)].Quantity & "available"
End If
MsgBox "Your hire request has been successful"
End Sub
Any help would be appreciated
You can achieve what you're asking by opening a recordset containing the results of a query and comparing the values returned by the query. In order to restrict the query to the proper quantities you need to pass in the ID of the tool you are checking.
#June7 is correct about saving calculated data. The only time you would want to save it is if you are keeping a log of events or if speed of join queries becomes an issue (unlikely given proper DB structure)
toolId might be stored in a text box control for example
Function Something_Click(toolId as string)
Dim rs as Recordset
' create a recordset containing data from the two tables
Set rs = CurrentDB.OpenRecordset("SELECT A.TOOL_QTY AS TOOL_QTY_A, " _
& " B.TOOL_QTY AS TOOL_QTY_B, A.TOOLNAME AS TOOLNAME" _
& " FROM TABLE1 AS A " _
& " INNER JOIN TABLE2 AS B ON A.TOOL_ID = B.TOOL_ID" _
& " WHERE A.TOOL_ID = '" & toolId & "'")
' compare the values in the table
If rs![TOOL_QTY_A] <= rs![TOOL_QTY_B] Then
' your true condition, for example
' MsgBox "Success"
Else
' your false condition, for example
' MsgBox "Oops, not enough of " & rs![TOOLNAME]
End If
' close the recordset
rs.close
End Function
I have one table in oracle database - which will have two columns (project name, view name). In that table when you filter project name, we will get all view names related to that project, based on those view names again we need to write query like select * from projectname$viewaname; to fetch that view related data.
Doing this manually is taking long time for each project. So my idea is to create MS ACCESS database to create tables for selected project and export them as excel files to C:\temp folder.
I need your help to create multiple tables in one go (using query/passthrough query or any other option) in MS Access fetching data from oracle database.
For that I have created MS access file, created one linked table (in which i have project and view names).
After that I have created one form, using project field as combo box from linked table and updated settings like, this form should be opened at start-up.
When I open access file, automatically this form is opening and asking me to enter oracle database user id and password - after entering credentials, combo box is updating and I can select my project in that list.
After that, I have created one query using main table and applied filter condition based on the selection in the form. Now I got results like project and view name for the end user selected project.
I need your help like,
now we have data in table like below.
Project | Viewname
A | A1
A | A2
A | A3
A | A4
A | A5
SQL query to see individual view data is :
select * from projectname$view_name;
ex: select * from A$A1;
project name, view name and no of rows(views), columns in views are dynamic - will change based on project.
I need your help to create multiple tables(one per one view) dynamically - Please suggest me the best option.
Regards,
Murali
Consider iteratively looping through the project/view name query in a recordset and creating the pass-through query that then exports to an Excel spreadsheet.
Public Sub ImportOracleProjectViews()
Dim db As Database, rst As Recordset, qdef As QueryDef
Dim constr As String, strSQL As String, mkTBL As String
Set db = CurrentDb
' ENTER QUERY HOLDING PROJECT AND VIEW NAMES '
Set rst = db.OpenRecordset("QUERYNAME")
' DELETE TEMP QUERYDEF IF EXISTS '
For Each qdef In db.QueryDefs
If qdef.Name = "temp" Then
db.QueryDefs.Delete ("temp")
End If
Next qdef
If rst.RecordCount = 0 Then Exit Sub
rst.MoveLast: rst.MoveFirst
' LOOP THROUGH EACH RECORD OF RECORDSET '
Do While Not rst.EOF
' SQL STATEMENTS '
strSQL = "SELECT * FROM " & rst!projectname & "$" & rst!viewname
' ORACLE CONNECTION STRING '
constr = "ODBC;Driver={Microsoft ODBC for Oracle};Server=myServerAddress;" _
& "Uid=myUsername;Pwd=myPassword;"
' PASS THRU QUERY '
Set qdef = db.CreateQueryDef("temp")
qdef.Connect = constr
qdef.SQL = strSQL
qdef.Close
' EXPORT TO MS EXCEL SPREADSHEET '
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, temp, _
"C:\Path\To\Output\Folder\" & rst!projectname & "_" & rst!viewname & ".xlsx", _
True
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
Set qdef = Nothing
Set db = Nothing
MsgBox "Successfully imported views to local tables and " _
& "Excel spreadsheets!", vbInformation
End Sub
Resources
Open Recordset VBA
Method
Oracle Connections
Strings
Creating Pass-Through Query in VBA Code
You have asked multiple questions, so the answer is structured correspondingly:
In order to create MS Access Table using VBA refer to the following sample code snippet:
Public Sub CreateTableVBA()
Dim SQL As String
SQL = "CREATE TABLE ThisTable " & "(FirstName CHAR, LastName CHAR);"
DoCmd.RunSQL SQL
End Sub
In order to create multiple Tables you should have an array of Table names and corresponding array of SQL statements, like the one shown above. Then you can loop through the array using VBA For-Next code block, running DoCmd.RunSQL command.
Alternatively, instead of DoCmd.RunSQL you may use Execute() function on VBA Database object, like shown below:
Sub CreateTableXSQL()
Dim dbs As Database
' include the path to MyDb.mdb on your computer.
Set dbs = OpenDatabase([Path to MyDb.mdb])
' create a table SQL with two text fields.
dbs.Execute "CREATE TABLE ThisTable " & "(FirstName CHAR, LastName CHAR);"
dbs.Close
End Sub
Hope this may help.
I have a form where a user selects a vendor's name from a combobox, whose catalog file is to be imported. The combobox selection then drives a query to create a one-record recordset (rsProfile) containing several profile variables queried from a table of all vendor profiles. These variables are then used in a series of different queries to reformat, translate and normalize the vendor's uniquely structured files to a standardized format that can be imported into our system.
I am frustrated that I can't figure out how to build my stored queries that will use one or more parameters that are automatically populated from the profile recordset.
Here is my rsProfile harvesting code. It works. Note that intVdrProfileID is a global variable set and used in other places.
Private Sub btn_Process_Click()
Dim ws As Workspace
Dim db, dbBkp As DAO.Database
Dim qdf As DAO.QueryDef
Dim rsProfile, rsSubscrip As Recordset
Dim strSQL As String
Dim strBkpDBName As String
Dim strBkpDBFullName As String
strBkpDBName = Left(strVdrImportFileName, InStr(strVdrImportFileName, ".") - 1) & "BkpDB.mdb"
strBkpDBFullName = strBkpFilePath & "\" & strBkpDBName
Set db = CurrentDb
Set ws = DBEngine.Workspaces(0)
MsgBox ("Vendor Profile ID = " & intVdrProfileID & vbCrLf & vbCrLf & "Backup file path: " & strBkpFilePath)
' Harvest Vendor Profile fields used in this sub
strSQL = "SELECT VendorID, Div, VPNPrefix, ImportTemplate, " & _
"VenSrcID, VenClaID, ProTyp, ProSeq, ProOrdPkg, ProOrdPkgTyp, JdeSRP4Code, " & _
"PriceMeth, " & _
"ProCost1Frml, ProCost2Frml, " & _
"ProAmt1Frml, ProAmt2Frml, ProAmt3Frml, ProAmt4Frml, ProAmt5Frml " & _
"FROM tZ100_VendorProfiles " & _
"WHERE VendorID = " & intVdrProfileID & ";"
Set qdf = db.QueryDefs("qZ140_GetProfileProcessParms")
qdf.SQL = strSQL
Set rsProfile = qdf.OpenRecordset(dbOpenSnapshot)
DoCmd.OpenQuery "qZ140_GetProfileProcessParms"
' MsgBox (qdf.SQL)
I have used QueryDefs to rewrite stored queries at runtime, and although it works, it is quite cumbersome and does not work for everything.
I was hoping for something like the sample below as a stored query using DLookups. I can get this to work in VBA, but I can't get anything to work with stored queries. I am open to other suggestions.
Stored Query "qP0060c_DirectImportTape":
SELECT
DLookUp("[VPNPrefix]","rsProfile","[VendorID]=" & intVdrProfileID) & [PartNo] AS VenPrtId,
Description AS Des,
DLookup("[Jobber]","rsProfile",[VendorID=" & intVdrProfileID) AS Amt1,
INTO tP006_DirectImportTape
FROM tJ000_VendorFileIn;
ADDENDUM:
Let me adjust the problem to make it a bit more complex. I have a collection of about 40 queries each of which use a different collection of parameters (or none). I also have a table containing the particular set of queries that each vendor 'subscribes' to. The goal is to have a database where a non-coding user can add new vendor profiles and create/modify the particular set of queries which would be run against that vendor file. I have almost 100 vendors so far, so coding every vendor seperately is not practical. Each vendor file will be subjected to an average of 14 different update queries.
Simplified Example:
Vendor1 file needs to be processed with queries 1, 2 and 5. Vendor2 file might need only update queries 2 and 4. The parameters for these queries might be as follows:
query1 (parm1)
query2 (parm1, parm4, parm8, parm11)
query4 (parm5, parm6, parm7, parm8, parm9, parm10, parm11)
query5 () -no parms required
This is the core query processing that loops through only the queries relevant to the current vendor file. rsSubscrip is the recordset (queried from a master table) containing this filtered list of queries.
' Run all subscribed queries
MsgBox "Ready to process query subscription list."
With rsSubscrip
Do While Not .EOF
db.Execute !QueryName, dbFailOnError
.MoveNext
Loop
.Close
End With
You can set the parameters of a predefined query using the syntax;
Set qdf = CurrentDB.QueryDefs(QueryName)
qdf.Parameters(ParameterName) = MyValue
To add parameters to the query, add the following before the SELECT statement in the sql
PARAMETERS [ParameterOne] DataType, [ParameterTwo] DataType;
SELECT * FROM tblTest;