Format Field to Days with VBA or SQL - sql

I am building a table in MS Access using SQL, one of the columns has a duration in days. I understand that if I build a new table with a Make Table Query, the column format properties just have to be set to #"days". Is there a way to do this in the code?
Dim tbl As String
tbl = "SELECT [Table1].[Task], [Table1].[Duration], [Table1].[Date] " & _
"INTO [" & all & "] " & _
"FROM [Table1]"
DoCmd.RunSQL tbl
When this code runs the new table converts Duration field to dates.
For Clarity: all is a variable name for the new table.
Thank you!!!

You can do with DAO. Open the TableDef and set the Format property of the duration field.
But you wouldn't have to. To view the data, create a query or form to view the data, and apply the format to the field or textbox displaying the duration.
Or create a query for the export:
Select *, Format([Duration], '0') & ' days' As Days
From YourTable
or even:
Select *, Format([Duration], '0') & ' day' & IIf([Duration] = 1, "", "s") As Days
From YourTable

Have you tried something like;
Sub Format_Dates()
Selection.NumberFormat = "[$-en-US]d-mmm-yy;#"
End Sub
"Selection" can be replaced by Range.NumberFormat.
(You would just need to find the date format you need. PowerSpreadsheets has a good article on this found here "Excel VBA Date Format")

I'd just store it as a number.
If you want to output it as a date, use the DateAdd("d", num-days, base-Date)

Related

Problem importing an excel workbook into Access and adding a column; error 3127

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.

ms access vba unique table naming method datestamp

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")

Date Order in Cross Tab Query - use Separate Table to Sort

I have a cross tab query with 'mmm-yyyy' formatted dates for Fields in the Columns.
I have used the below Design to create the query.
Cross Tab Design View
The problem I am having is the dates are not sorting correctly from Dec-17 down to Jul-16 in descending order. This is going to be a dynamic query with months changing every month so I want to use an additional table of data to do the sorting (as opposed to entering a list of month names in the Properties window).
How would I fix my query to get it to do this please?
Thanks for your help
Unfortunately, no matter how joined tables are sorted, crosstab will sort columns by default in alphabetical order, hence Apr, Dec, ... begins the order. To change or even filter column order in crosstabs, you would specify values in PIVOT Col IN () clause of SQL statement.
Since you need a dynamic query consider creating a querydef in VBA to update the SQL behind the crosstab where you dynamically update the PIVOT Col IN () clause. Of course, pass begin and end dates as needed or by parameters:
Public Sub BuildCrossTab()
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String, dates As String
Dim i As Integer, monthsDiff As Integer
Set db = CurrentDb
' DELETE PREVIOUS SAVED QUERY
For Each qdef in db.QueryDefs
If qdef.Name = "AccuralsCrosstabQ" Then
db.Execute "DROP Table " & qdef.Name, dbFailOnError
End If
Next qdef
' LOOP THROUGH ALL MONTHS BACKWARDS
dates = "("
monthsDiff = DateDiff("m", #7/1/2016#, #12/1/2016#)
For i = monthsDiff To 0 Step -1
dates = dates & " '" & Format(DateAdd("m", i, #7/1/2016#), "mmm-yyyy") & "',"
Next i
dates = dates & ")"
dates = Replace(dates, ",)", ")")
' PREPARE SQL STRING
strSQL = "TRANSFORM SUM(a.[Amount $]) AS SumAmount" _
& " SELECT a.Company, a.[Accrual ID], SUM(a.[Amount $]) As [Total Amount $]" _
& " FROM [Accruals Raw Data] a " _
& " GROUP BY a.Company, a.[Accrual ID]" _
& " PIVOT Format(a.[Posted Date], ""mmm-yyyy"")" _
& " IN " & dates
' CREATE QUERY
Set qdef = db.CreateQueryDef("AccuralsCrosstabQ", strSQL)
Set qdef = Nothing
Set db = Nothing
End Sub

Use a Field in main Table to Update a Field in Another Table in Access

I have three tables in Access DB, "tbl_BO" which is linked to Excel sheet which is updated every monday, "tbl_KPI1" and "tbl_KPI2. Every table has field called "CW", means calendar week. "tbl_BO" has all the same fields which has other two tables.
I want to run a macro by clicking a buttom which does the following: For example for "tbl_KPI1".
Lookup "CW" from last week (in this case 2016.44) in "tbl_BO", match it with "CW" of "tbl_KPI1", and update the field "115p".
Below, I have written a code, which is running all the values in that field ("115p"). But as I said I want to update the values only from last week (ISO week)
Public Function Update()
DoCmd.SetWarnings False
DoCmd.RunSQL "Update tbl_KPI1 INNER JOIN tbl_BO " & _
"ON tbl_KPI1.CW = tbl_BO.CW " & _
"SET tbl_KPI1.115p = [tbl_BO].[115p] "
'Here come codes to update the fields of other tables, same logic
DoCmd.SetWarnings True
End Function
And my ISO week code is:
Function ISOweek(ByVal Dat As Date)
ISOweek = Int((Dat - Weekday(Dat, vbMonday) + 11 - _
DateValue("jan 01," & Year(Dat + 4 - Weekday(Dat, vbMonday)))) / 7)
End Function
How can I make a combination of both codes in order to achieve what I want. Or any ideas how to do it? Thanks.

where clause in select statement - datetime issues

I want to put a where clause in my select statement based on the year and month of a timestamp field in my db
I have a month and a year dropdownlist which give me the following string 01/2012
The date format in my db is "2012-01-01 00:00:00" but when I select an individual date and put it in a message box it converts to "01/01/2012"
I've altered my select statement below to reflect the converted date. However Im still not given the correct details. Any ideas? Is there a particular format that I need to use when dealing with a timestamp field? Can I even use the "Right" function in a select statement?
Dim newRecordDate As String = val1 & "/" & ComboBox2.SelectedValue
Dim sql2 As String = "Select CatA, CatB, CatC, Cost, Currency, MarketingCode, Comment, RecordDate from vw_tblP_Usage_Details where puid = '" & puid & "' right(RecordDate, 7) = '" & newRecordDate & "'"
I say use parameters and the SqlParameter class to pass parameter values to sql server from .NET client instead of using concatenation and string formatting. It makes life easier.
Something Like This:
Dim myDate As Date = DateTime.Now
Dim sql As String = "Select * from SomeTable where MyDate = #some_param"
Using Command As New SqlClient.SqlCommand(sql)
Command.Parameters.AddWithValue("#some_param", myDate)
Using reader As SqlClient.SqlDataReader = Command.ExecuteReader()
'other code here
End Using
End Using