ms-access,pivot-table , Derive two hours time blocks from start and end time fields

Derive two hours time blocks from start and end time fields


Tag: ms-access,pivot-table

I have a table in Microsoft Access that has a list of volunteers for an event. The table contains fields such as name, phone number, etc. There are three additional fields; Assignment which describes what activity the volunteer will be assigned to. For example, parking, front gate, ticket Booth, etc. The two other fields, start and end time describe when a volunteer is able to work.

Is it possible to write a query - maybe some sort of pivot table - that has 2 hours time slots as the row header and some sort of true/false value if the time slot has been filled for the assignment? The event is from 6am to 6pm.

For example:

Assignment | 0600 | 0800 | 1000 | 1200 | 1400  | 1600 
Parking    |  X   |  o   |   X  |  X   |   X   |   X  
TicketBooth|  o   |  o   |   X  |  o   |   X   |   o  

I'm trying to group volunteers by their assignment and derive two hour time blocks from the start and end time of each volunteer and generate a report which would allow the event coordinator to easily distinguish whether they would need to add a volunteer to the assignment.

The volunteers table structure looks like this:

FirstName | LastName | Assignment   | StartTime | EndTime
Joe       | Smith    | Parking      | 1000      | 1800
Jessica   | Anderson | Parking      | 0600      | 0800
Ryan      | Webber   | TicketBooth  | 1000      | 1200
Michael   | Flent    | TicketBooth  | 1400      | 1600

Is it possible to generate a query to get the results shown in the example above given the table structure? If not, what would I need to modify?


Okay, so given your sample data, a Pivot table is not ideal because the lack of a table/join table with times and who can work when, etc.

So, I created a function that returns "o" or "x" depending on if someone's availability fits into the time slots you've provided us an example with. The only bad thing is that you have to manually create a column for each time slot. That would have been the nice thing with a Pivot table.

This could have been done using an IIf() as well. Here's a quick example of that:

SELECT volunteers.Names,
       IIf(1800>=[Start] And 1800<=[End],"Can Work","Can't") AS 1800
FROM volunteers;

Anyway, here's the function (I didn't handle any errors) :

Option Compare Database
Option Explicit

Public Function IsAvailable(time, starttime, endtime) As String

Dim AvailableTime, StartingTime, EndingTime As Integer

AvailableTime = time
StartingTime = starttime
EndingTime = endtime

If AvailableTime >= StartingTime And AvailableTime <= EndingTime Then
    IsAvailable = "o"
    IsAvailable = "x"
End If

End Function

How you can use it with a query:

SELECT volunteers.Names, 
       IsAvailable(600,[Start],[End]) AS 0600, 
       IsAvailable(800,[Start],[End]) AS 0800, 
       IsAvailable(1000,[Start],[End]) AS 1000, 
       IsAvailable(1200,[Start],[End]) AS 1200, 
       IsAvailable(1400,[Start],[End]) AS 1400, 
       IsAvailable(1600,[Start],[End]) AS 1600, 
       IsAvailable(1800,[Start],[End]) AS 1800
FROM volunteers;


enter image description here

Note: I used Start and End for my column names in my table, so you would have to change [Start] and [End], respectively.

Also, I don't personally think this is the best solution. I think if you knew this data was required to be in this format I would have probably designed my database for it, but this is kind of a crude work-around.


Access filter on time

I have a table with a time in a datetime field on an MSSQL2k8R2 server. I have linked the table in Access 2007. The table was migrated with the migration assistant from Microsoft. i.e. the Managemantstudio will give on SELECT TOP 3 [AbZeit], [AbBrP] FROM [dbo].[tSollFahrten] the Result AbZeit AbBrP...

ms access query very slow

I have this ms access query: SELECT, suchbegriff2, menge FROM (SELECT artnr & '/' & [lfdnr-kal] AS sb, left(suchbegriff,7) & val(right(suchbegriff,4)) AS suchbegriff2 FROM kvks WHERE suchbegriff like '*/*') AS t1 INNER JOIN (SELECT artnr & '/' & [lfdnr-kal] AS sb, [artnr-hz] & '/' & val(lfdnr) AS hz, menge...

How to insert only time in ms access?

This is the query I am having issues with: cmd = new OleDbCommand(insert into tbl_Customer(cReportingTime) values (@ReportingTime)", con); cmd.Parameters.Add("@ReportingTime", OleDbType.DBTime).Value = Time; cmd.ExecuteNonQuery(); When I try to run it I am getting this error: "Failed to convert parameter value from a DateTime to a TimeSpan" I want to insert only...

How to count multiple values in one single cell using Pivot Tables in Excel?

I have this table in a Excel sheet: I would like to create a Pivot Table to have this outcome: Do you guys have any idea how to do it? Thank you!...

Get the VBProject of a Database

Given a database object in MS Access VBA, how can one get that database's VBProject? Function GetVBProject(ByVal db As Database) As VBProject Set GetVBProject = ??? End Function The only way I know how to get VBProjects in Access is through Application.VBE.VBProjects.Item(???). However, I won't know what order of the...

ACCESS: calculate timestamp difference between rows

Here is the data I am working with in MS Access from a system tracking when a agent makes system changes: |agentid|eventtype|reasoncode|eventdatetimelocal | |1830 |2 |32762 |01/01/2014 7:11:44 PM| |1830 |3 |0 |01/01/2014 7:13:46 PM| |1830 |2 |32762 |01/01/2014 7:14:55 PM| |1833 |2 |0 |01/01/2014 7:11:35 PM| |1833 |3 |32762...

How to create a date using strings in vba?

I want to run a for-loop from sometime to some specific time. Let's say from the first day of the year to the last day: I am given the year and I need to add the month and the day to it: I am trying to concatenate into a full...

Converting ADODB Loop into DAO

Hi I've been developing a vba project with a lot of help from examples here. I'm trying to access a MS Access database from Excel VBA and import large data sets (500-100+ rows) per request. Currently, the following loop works using ADODB however, the Range("").Copyfromrecordset line is taking very long...

Getting value of Date Time Picker and using BETWEEN for filtering date in Ms Access database,ms-access,oledb
I have a From and To DateTimePicker. I converted them into a String and use it to filter a MsAccess database of a specific range but there is a problem with the filtering. For example, I would like to filter from January 1, 2015 to January 31, 2015. The results...

MS Access Text Field Special Characters

I have a search button that executes this applyfilter macro code: [ContractNumber] Like "*" & [Forms]![frmContractMatch&Revenue]![Text44] & "*" So it searches text box text44 for the appropriate ContractNumber. The trouble I am having is that if a contract number is ART#45 for example, it will not find it in the...

Iterate Databases and Delete Query

I am trying to iterate a table with database names in it, open the database, check if a query exists, if it does delete it, then import a query from the database this code is being executed from. I keep getting a compile time error on the line of Set...

Add 1 to datediff result if time pass 14:30 or 2:30 PM

Here is my SQL query which returns number of days by subtracting current date from specified date and returns exact as i need, but in addition i want to add 1 to result if current time passes 14:30 or 2:30. My query SELECT reservations.customerid, DateDiff("d",reservations.checkin_date,Now()) AS Due_nights FROM reservations Am...

Importing data from access to excel using vba

I am trying to import data from the table "memory" in my access database called "Computer.accdb", which is located on the desktop to Excel. I was able to find a code online and it was able to run but it did not work properly. I added a reference to the...

VBA to change Pivot Filter in OLAP cube to a range

I have a pivot table that pulls data from an OLAP cube, and I'd like to create a macro to filter a pivot field that contains 'Week of Year' based on the value in another cell, so that I can easily change the time frame of the table. My experience...

Database only adds (x) amount of rows before error system resources exceeded

I am having a problem with my code where i am only able to add so many lines of text before i get an error "system resources exceeded". This is my code: Dim x As Integer = MsgBox("Update Record?", MsgBoxStyle.YesNo, "Are you sure?") If x = MsgBoxResult.Yes Then Dim accessconn...

Extract matching data from varying number of row

I am trying to build graphic indicators from a (potentially) large set of data using google-spreadsheet. So far, I've used a pivot table to extract the information from the raw data, and I want to build intermediate tables to calculate the different values I need for my indicators. So far,...

Extracting data from Excel to Access Database

There is a standard company form currently in Word format (could use a different technology) with fields. How do I extract the data into my Access DB from this fields?. I am also open to advice of which technology would suit my requirements better with the requirements being: Need document...

How do I resolve the “Enter Parameter value” error in MS-Access

This code and another is producing the logical error in Ms-Access where it asks for a parameter equal to an objects name. In this case it wants [DSRT_ERS].[ID]. INSERT INTO DSRT_ERS SELECT * FROM DSRT_TEMP WHERE [DSRT_ERS].[ID] <>[DSRT_TEMP].[ID]; If you look at the DB's documentation you notice it is spelled...

In SQL how do I update a table with a similar table?

In my current Database I have a table whose data is manually entered or comes in an excel sheet every week. Before we had the "manual entry option", the table would be dropped and replaced by the excel version. Now because there is data that only exists in the original...

Quartile/Percentile in MS Access via SQL with a GROUP BY when some values can be NULL

I am looking to calculate a percentile of a subgroup for a field that can be NULL. Field IU is either 1 or Null. Specifically: *my table: tblFirst250 *group by: IU = 1 (which is Nullable) *percentile of: GM (which is Nullable) I am starting with the following (but I...

Get a Count of a Field Including Similar Entries MS Access

Hey all I'm trying to parse out any duplicates in an access database. I want the database to be usable for the access illiterate and therefore I am trying to set up queries that can be run without any understanding of the program. My database is setup where there are...

Recordset.Edit or Update sql vba statement fastest way to update?

I recently came across vba update statements and I have been using Recordset.Edit and Recordset.Update to not only edit my existing data but to update it. I want to know the difference between the two: recordset.update and Update sql Vba statement. I think they all do the same but I...

Update query when database in ms access

My update query update tbl_Clients set [email protected], [email protected] where [email protected] When I am updating this code in giving error Syntax error in update statement...

Calling MS Excel function from MS Access VBA

I am working an MS Access application a part of which uses Beta Distribution function. Since MS Access does not have Beta Distribution function of its own I'm using calling BetaDist function from MS Excel. I've tested the code in MS Excel and it seems to run successfully. In MS...

Im trying to populate a Sharepoint list with the most upcoming dates from certain colums of data from another Sharepoint list?

I have a list named Employee Dates, this list contains the columns: Employee | CPR Completed | CPR Required | ETC These columns keep going on for all of the training courses required for our employees with alternating columns for completed and required dates. I am using a workflow to...

Get work time in minutes based on shift schedule

In production we have 3 shifts. Each Shift timing is described in table tbl_ShiftSched: WT - work time, PT - break time. ShiftTmID - schedule for 2 and for 3 shifts. I am looking for easy way to get work time in minutes having start and end time. For example,...

How to execute four queries once and then check success or failure?,windows,visual-studio-2010,ms-access
I need to execute four queries and then if there is success must return true otherwise false. The queries affect the database but the function returns false Private Function save_to_data() Dim success As Boolean = False Dim conn As OleDbConnection = GetDbConnection() Dim total_due As Decimal = sanitize(txt_total_due.Text) Dim amount_paid...

Using date in CreateQueryDef

I have a table on which I run a query that I export to Excel. Here is an example: Table: Food Item | Price | Limit_Date | ------------------------------- Carrot | 0.80 | 08/07/2015 | Salmon | 4.30 | 01/07/2015 | Biscuits | 2.40 | 15/12/2015 | Milk | 1.00 |...

Running Access from Command line but not loading it?

I would like to launch a MS Access macro from the command line (it's being run from another tool) to generate an output. Thing is, I'd prefer it if it could supress access from loading it's interface. I just want it to run the macro and shut down. Any thoughts...

Run various queries based on a combo box selection

I have a form where a user will select a value from a dropdown. Based on this selection, I would like a series of queries to execute. For example, if a user selects 'A', then queries 1, 2 and 4 would execute. If user selects 'B', then queries 4, 2,...

VBA keeping excel files locked from myself after code

I've been running into issues with this code. It works fine if I restart the computer and run it, but once the code has been run once it starts to cause errors. I will either get either the "save error" or the "admin error" because the file (either the original...

Editing a query in another DB

Is it possible to open a second Access database from within an Access database, and edit a query in that second DB? I know you can open one Access DB from another, but I'm just not sure whether or not you can edit a query that way. If it's possible,...

How to calculate number of days by subtracting date_time field from current date_time?

I have reservations table to store hotel reservations, this table has reservation_id, customer_id, rommno, and checking date also there is another optional field, checkout field which will use when person checked out and also the status field will updated to checkout status wile firstly putted checking status. i need a...

VBA - Using Typeof … Is ADODB.Recordset Results in Compile Error

I am building a function with a set of supporting sub-functions to create ADOX.Catalog objects to help me build automation for Access database generation. I like to use late-binding for my applications because my user base doesn't always have the same version of office applications, so I can't always rely...

I need help setting the RecordSource of a Report within a VBA Function

Ok, so I've been looking around here for a few days (and a few other sites) and while I have modified my code a good bit to find a solution, it still doesn't work. I have four source queries, and I'd like to set the record source of my report...

SQL Update query on query result

I have 2 tables like: Table 1 SID Sdefinition CValue 4057 s1 32 4058 s2 4059 s3 6 4060 s4 Mapping_tbl SID SINID ECFID SID-SINID 4057 1099 4027e 1099_4057 4058 1099 4027e 1099_4058 4059 1121 4003e 1121_4059 4060 1121 4003e 1121_4060 Query1 SELECT Mapping_tbl.SID, Table1.Sdefinition, Table1.CValue FROM Table1 INNER JOIN...

Connecting to ODBC using pyODBC

I've read all the faq pages from the python odbc library as well as other examples and managed to connect to the DSN, using the following code: cnxn = pyodbc.connect("DSN=DSNNAME") cursor = cnxn.cursor() cursor.tables() rows = cursor.fetchall() for row in rows: print row.table_name but for everything else I keep getting...

for-loop add columns using SQL in MS Access

I am trying to add n columns to a table, like in this example of code where n = 10: Sub toto() Dim db As Database, i As Integer Set db = CurrentDb() For i = 1 To i = 10 db.Execute " ALTER TABLE time_series " _ & "ADD...

pass parameters to record source with query Access2007

I am relatively new to access and I have been tasked to improve the navigation of the app. I have a form which is used to open the report. The record source of the report is as follows, SELECT Projects.Project_Number, Projects.Customer, Projects.End_User, Projects.Engineering_Company, [Merged Ship and Delivery Dates].Sched_Next_Delivery_Date, [Merged Ship...

Adding Access totals cause report to not run

I am trying to add a few totals (sums and counts) using the wizard to an Access report. When I add them to the report and try to view the report, the report fails. Without the totals the report will display. The only thing I can figure that may be...

Create Table - Time Statement

I am having trouble trying to create a table using MS Access. I know for sure my problem lies in the "datetime" field but I can not figure what I am missing or doing wrong. When I click "run" I get the "Syntax Error in Field Definition" Create Table Appointments...

Select Query Doesn't Show All Results

I have a combobox on a subform (ProgramSubform) in Access that's supposed to list report years for a project from a table (Program). Most projects have more than one report year, but the combobox always brings only 2014. For example, the dropdown for project 5278 should be: 2012 2013 2014...

Javascript ADO recordset open method not working. Parametrized queries

I am creating a web page and have some javascript code to insert some information from the webpage to MS access database. I am using ADO connections and record set but I am having a problem with the open method. This is a snippet of the code I am having...

Adding a column to existing table in access without using any relationship

I am working on a project in ACCESS 2010 that requires me to give a rank to 30000 products based on their sales. I have tried using a query to do the ranking and it takes a long time. (Please find codes at Making the ranking query efficient) I figured...

Laravel 4 - Scope to only show rows where another DB has no relational items

I have a cars table, and a car_image table. I want to get all the cars that have NO images in the car_image. In my car model I am making a scope: public function scopeNoImages($query) { return $query-> ?? } How can I create a scope that will show only...

what will be the select query for excluding empty values in ms access

I am trying select * from table where Contact Is Not null but it is displaying values including empty values...

SQL for Aggregate 25 percentile value for subsets in MS Access?

This gets the 25th percentile value of the GM field when field GICS Sector = "Energy": SELECT tblFirst250.[GICS Sector] , 0.75*( SELECT Max(GM) FROM tblFirst250 WHERE tblFirst250.GM IN ( SELECT TOP 25 PERCENT GM FROM tblFirst250 WHERE tblFirst250.[GICS Sector ]= "Energy" AND GM Is Not Null ORDER BY GM)) +...

Photos as Varbinary(MAX) in SQL Server 2012 causes error 502753 in Access 2010

I have an Access 2010 odbc front end with a SQL Server 2012 back end. My images (.bmp) are stored as Varbinary(Max). When I insert an image using my bound object frame in an Access form, the image displays on the form and report perfectly. I had a large number...

How to set primary key when linking with CreateTableDef

In a MS Access database, I'm connecting to views in a SQL Server database like this: Dim s As String s = "ODBC;DSN=mydb;Trusted_Connection=Yes;DATABASE=mydb;" Dim td As TableDef Set td = CurrentDb.CreateTableDef("vwMyView", 0, "MySchema.vwMyView", s) CurrentDb.TableDefs.Append td CurrentDb.TableDefs.Refresh This creates a linked table, which is linked to a view in SQL...

Verify If New Record Access 2010

I have a table created to hold all my client data. The data is all entered in via form. When a new record is created (new client added) I also need to create an opening transaction balance on a separate table. So what is the best way to... 1) Identify...