How to display date as text in Access report - ms-access

I'm trying to get Access to create a certificate for me. I've got almost everything worked out except for the date. I want the date to display as text.
I'm able to accomplish this with a module in Excel, but when I input it into Access as a function, it gives me a #Name? error. Here's what I have in the function (again, this works in Excel):
Function DateToWords(ByVal xRgVal As Date) As String
Dim xYear As String
Dim Hundreds As String
Dim Decades As String
Dim xTensArr As Variant
Dim xOrdArr As Variant
Dim xCardArr As Variant
xOrdArr = Array("1st", "2nd", "3rd", "4th", "5th", "6th", _
"7th", "8th", "9th", "10th", "11th", "12th", _
"13th", "14th", "15th", "16th", "17th", "18th", _
"19th", "20th", "21st", "22nd", _
"23rd", "24th", "25th", "26th", _
"27th", "28th", "29th", "30th", "31st")
xCardArr = Array("", "one", "two", "three", "tour", _
"five", "six", "seven", "eight", "nine", _
"ten", "eleven", "twelve", "thirteen", _
"fourteen", "fifteen", "sixteen", _
"seventeen", "eighteen", "nineteen")
xTensArr = Array("twenty", "thirty", "forty", "fifty", _
"sixty", "seventy", "eighty", "ninety")
xYear = CStr(Year(xRgVal))
Decades = Mid$(xYear, 3)
If CInt(Decades) < 20 Then
Decades = xCardArr(CInt(Decades))
ElseIf CInt(Decades) Like "*0" Then
Decades = xTensArr(CInt(Left$(Decades, 1)) - 2)
Else
Decades = xTensArr(CInt(Left$(Decades, 1)) - 2) & "-" & _
xCardArr(CInt(Right$(Decades, 1)))
End If
Hundreds = Mid$(xYear, 2, 1)
If CInt(Hundreds) Then
Hundreds = xCardArr(CInt(Hundreds)) & " hundred "
Else
Hundreds = ""
End If
DateToWords = "This " & xOrdArr(Day(xRgVal) - 1) & " day of" & _
Format$(xRgVal, " mmmm, ") & _
xCardArr(CInt(Left$(xYear, 1))) & _
" thousand " & Hundreds & Decades
End Function
Code in Access that calls the function. This is in the text box on the report:
=DateToWords([Forms]![FrmMakeCert]![Date])
n Excel, this takes the date that I specify in a cell (e.g. 12/27/18) and turns it into:
"This 27th day of December, two-thousand eighteen"
That's what I'd like to accomplish in the Access report, pulling the date from a form.

Issue was caused by using the same name for both user-defined function and module namely DateToWords.
You should use different names.
Rename the module to, for instance, mdlDateToWords.

Steps to use.
First create a module in access and paste your codes.
Suppose in report you are displaying date to text in a textbox name txtDateText
In txtDateText data source enter following
=DateToWords([Forms]![Form1]![txtDate])
Remember: Form1 must be open and contain valid date otherwise it will show error. Form1 is form name, so it will be different in your case. Also text box name.
File download link

Related

Access date comparison does not work for specific dates

I made a form to update historical data and a subform that is used to check the result! Everything works fine except one small problem.
The result of my date comparison is not correct for any date that is the first date of any month in 2018!!! (it is driving me craziee)
So my code is below:
Private Sub runbtn_Click()
Me.Refresh
Dim theminimum As String
Dim theprodscID As String
Dim thepurchasedate As Date
If IsNull(Me.purchasedate) = False Then
theprodscID = Str(Me.prodscID)
thepurchasedate = Me.purchasedate.Value
'minimum textbox
theminimum = "Select Top 1 [update value]" & _
" From [product and shareclass level data update]" & _
" Where [product and shareclass level data update].[dataID] =" & Str(1) & _
" And [product and shareclass level data update].[prodscID] =" & theprodscID & _
" And ([product and shareclass level data update].[timestamp] <= #" & thepurchasedate & "#)" & _
" Order by [product and shareclass level data update].[timestamp] DESC"
If CurrentDb.OpenRecordset(theminimum).RecordCount = 0 Then
Me.minimum = Null
Else
Me.minimum = CurrentDb.OpenRecordset(theminimum).Fields(0).Value
End If
So for example, if I have records update value: "hello" on 01/05/2018; "bye" on 01/08/2017. Then, when I enter the purchase date as 01/05/2018, it should give me "hello" but not "bye"! However, if I enter 12/05/2018, it gives me "hello", which is correct! I find that this error occurs for some dates that I put as timestamp, but works for other dates!
I checked my code and I think it is correct. I don't know what the problem is!
Thanks,
Phylly
Your problem is, that the date value must be properly formatted as a text expression. thus:
" And ([product and shareclass level data update].[timestamp] <= #" & Format(thepurchasedate, "yyyy\/mm\/dd") & "#)" & _
Alternatively, implement my function CSql, or - even better - start using parameters (bing/google for that).

VBA SystemTime - 30 days

I am working on a code from a previous developer. This code has SystemTime set up.
Is there a way to get today date and minus 30 days in this format?
Code Below:
Public Function GetIsoTimestampTest() As String
Dim st As SYSTEMTIME
'Get the local date and time
GetSystemTime st
'Format the result
GetIsoTimestampTest = _
Format$(st.wYear, "0000") & "-" & _
Format$(st.wMonth, "00") & "-" & _
Format$(st.wDay, "00") & "T" & _
Format$(st.wHour, "00") & ":" & _
Format$(st.wMinute, "00") & ":" & _
Format$(st.wSecond, "00") & "Z"
End Function
Build a native date & time, add -30 days, format as a string:
utcInIsoFormat = Format$(DateAdd("d", -30, _
DateSerial(st.wYear, st.wMonth, st.wDay) _
+ TimeSerial(st.wHour, st.wMinute, st.wSecond)), "yyyy-mm-ddThh:nn:ssZ")
SYSTEMTIME appears to be a custom type defined elsewhere in your code. It's not a standard type available in Access VBA. So to use it effectively, you need to find the definition. Also GetSystemTime is also likely a custom function exclusive to your code. Here's a sample definition of a similar type, although it may not be exactly what's implemented in your system: http://custom-designed-databases.com/wordpress/2011/get-milliseconds-or-seconds-from-system-time-with-vba/
That said, System Time would refer to the Windows system time. You also have a native ability in VBA to get time using the Now() function. (https://msdn.microsoft.com/en-us/library/office/gg278671.aspx) This returns a variable with type Date, which is equivalent to a number where the integer represents days and the decimal represents time of day. An example to get 30 days prior to today would be:
Dim lastMonth as Date
Dim formattedDate as String
lastMonth = Now() - 30
formattedDate = Format(lastMonth, "yyyy-mm-ddThh:nn:ssZ")
DateSerial happily accepts a negative day count. Thus:
Public Function IsoDateMinus30() As Date
Dim st As SYSTEMTIME
Dim Result As Date
' Get the local date and time
GetSystemTime st
Result = DateSerial(st.wYear, st.wMonth, st.wDay - 30)
' To include time:
'
' Result = _
' DateSerial(st.wYear, st.wMonth, st.wDay - 30) + _
' TimeSerial(st.wHour, st.wMinute, st.wSecond)
IsoDateMinus30 = Result
End Function

Join two worksheets; first contains a list of ranges, second contains data that may fall within in range of the first

I'm working on combining two excel worksheets. Before I start, I'd like to mention that I also have mysql workbench, so I'm open to working on this issue in either sql or vba (I should learn both). I'm working with .bed files, which are lists of genomic coordinates. In short, the data is indexed by chromosome number (ie:chr2) and then has a numerical start and stop location on the chromosome. These numerical locations can span a large range (ie:100-10,000) or be a single position (ie: 999-1000). I have a list of coordinates that cover a large range, and in a separate file I have a list of single positions.
Example of a file with ranges:
chromosome start stop
chr1 4561 6321
chr3 9842 11253
Example of file with single positions:
chromosome start stop
chr1 5213 5214
chr3 10254 10255
I would like to combine these worksheets such that if a location in my list of single positions is found within the range in my list of ranges, the locations for both are listed in the same row. The lists are 1000s of locations long, so I'd also like this program to loop through every row. Using the example data listed above, I'd like my output to look like the following:
Example of desired output:
chromosome start stop chromosome start stop
chr1 4561 6321 chr1 5213 5214
chr3 9842 11253 chr3 10254 10255
There is a high probability that multiple single positions will fall within a single range, and I would like these to be listed as separate rows.
I appreciate any help I can get! Thank you in advance. I am eager to learn!
Here's a basic outline which queries two tables on sheets named "Ranges" and "Positions", and outputs the results on a sheet named"Results"
The input tables should have headers, and start in the top-left cell (A1)
Sub SqlJoin()
Dim oConn As New ADODB.Connection
Dim oRS As New ADODB.Recordset
Dim sPath
Dim sSQL As String, wb As Workbook
Set wb = ThisWorkbook
sSQL = " select a.chromosome, a.start, a stop," & _
" b.chromosome, b.start, b.stop " & _
" from <ranges_table> a, <positions_table> b" & _
" where b.start >= a.start and b.stop <= a.stop"
sSQL = Replace(sSQL, "<ranges_table>", _
Rangename(wb.Worksheets("Ranges").Range("A1").CurrentRegion))
sSQL = Replace(sSQL, "<positions_table>", _
Rangename(wb.Worksheets("Positions").Range("A1").CurrentRegion))
If wb.Path <> "" Then
sPath = wb.FullName
Else
MsgBox "The workbook must be saved first!"
Exit Sub
End If
oConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & sPath & "';" & _
"Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"
oRS.Open sSQL, oConn
If Not oRS.EOF Then
wb.Worksheets("Results").Range("A2").CopyFromRecordset oRS
Else
MsgBox "No records found"
End If
oRS.Close
oConn.Close
End Sub
Function Rangename(r As Range) As String
Rangename = "[" & r.Parent.Name & "$" & _
r.Address(False, False) & "]"
End Function

How to select the file whose name includes the newest date?

I am importing a CSV file into a table in MS Access.
However there are many files in the folder with the same extension and the names include dates in "mm_dd_yyyy" format.
Example: Lets say I have two CSV files:
my_music_02_10_2013_01_58_07_PM.csv
my_music_02_11_2013_03_04_07_PM.csv
Both files are in the same folder, myfolder. I want to import the file whose name contains the newest date.
Here is a short snippet of my code:
strPath = "F:\myfolder\"
strFile = Dir(strPath & "my_music" & "*.csv")
How can I determine which of my "my_music*.csv" is newest?
Seems to me the key is to extract the Date/Time from each file name so that you may compare those to find which of them is newest.
Here is an Immediate window session testing the function included below. The function returns null if it can't find a string which represents a valid date.
? DateFromFilename("my_music_02_10_2013_01_58_07_PM.csv")
2/10/2013 1:58:07 PM
? DateFromFilename("my_music_no_date_here.csv")
Null
Public Function DateFromFilename(ByVal pFileName As String) As Variant
Dim strBaseName As String
Dim strDate As String
Dim strPieces() As String
Dim varReturn As Variant
varReturn = Null
strBaseName = Split(pFileName, ".")(0)
'Debug.Print "strBaseName: " & strBaseName
strPieces = Split(strBaseName, "_")
If UBound(strPieces) = 8 Then
strDate = strPieces(4) & "-" & strPieces(2) & _
"-" & strPieces(3) & " " & strPieces(5) & ":" & _
strPieces(6) & ":" & strPieces(7) & " " & strPieces(8)
End If
'Debug.Print "strDate: " & strDate
If IsDate(strDate) Then
varReturn = CDate(strDate)
End If
DateFromFilename = varReturn
End Function

Delete unwanted Columns and add some text to 1st column of a csv

I have a csv file.There are many columns like "Commodity" , "Ex-basis delivery centre", "Price unit" etc I don't want and I want to delete. How can this be done
Also I want to add 1,2,3 such numbers as per expiry to the first column. Example:
SYMBOL EXPIRY
BARLEYJPR 8/17/2012
BARLEYJPR 9/20/2012
BARLEYJPR 10/19/2012
BARLEYJPR 11/20/2012
In first line I would like to add 1 to BARLEYJPR as the expiry is on august 17th 2012(8/17/2012) which is nearest of all then would like to add 2 to BARLEYJPR as expiry is in September then would like to add 3 to BARLEYJPR as expiry is in October and lastly 4 to BARLEYJPR as expiry is in November.
Can someone help me? I'M LOOKING FOR CODE IN VB6 AS I HAVE ALREADY WRITTEN CODE IN VB6 TO DOWNLOAD FILES FROM THE WEBSITE.
Private Sub Command1_Click()
On Error GoTo Err
Const q As String = "-"
Dim tmp As String, fName As String, Pos As Long, fPath As String
Dim first As Date, last As Date, spath As String, d As Date
cap = Me.Caption
If Dir(App.Path & "\NCDEX\") = "" Then
MkDir App.Path & "\NCDEX\"
End If
spath = App.Path & "\NCDEX\" ' folder to save files : note trailing \
first = MonthView1
last = MonthView2
'http://www.ncdex.com/Downloads/Bhavcopy_Summary_File/Export_csv/07-04-2012.csv
strURL = "http://www.ncdex.com/Downloads/Bhavcopy_Summary_File/Export_csv/"
For d = first To last
ssourceurl = strURL & Format(d, "MM") & q & Format(d, "dd") & q & Format(d, "yyyy") & ".csv"
fName = Format(d, "dd-mm-yyyy") & ".csv"
slocalfile = spath & fName
Me.Caption = "Downloading " & fName
Call DeleteUrlCacheEntry(ssourceurl)
URLDownloadToFile 0&, ssourceurl, slocalfile, BINDF_GETNEWESTVERSION, 0&
Debug.Print ssourceurl
Next
Me.Caption = cap
'YOU CAN TAKE THIS BELOW OUT IF U DONT WANT IT
MsgBox "Saved to " & spath, vbInformation + vbOKOnly, "Success!"
Exit Sub
Err: MsgBox "Error", vbCritical + vbOKOnly, "Market Was Closed"
End Sub
You could make use of the Jet engine to read the CSV file to a recordset and manipulate it like you do with a database using ADO.
Some examples and reference sites:
http://www.freevbcode.com/ShowCode.asp?ID=2180
http://www.codeproject.com/Articles/26822/Read-Text-File-txt-csv-log-tab-fixed-length
http://www.vbforums.com/showthread.php?t=674758