Date format Shows Invalid Date With Custom Date. When I use 'Date' instead of "25th May" it shows yesterday's Date.
function GetYD()
Dim dt, yesterday
dt = DateAdd("d", -1, "25th May")
yesterday = Right(Year(dt),2) & Right("0" & Month(dt),2) & Right("0" & Day(dt),2)
msgbox yesterday
GetYD = yesterday
end function
Be sure to feed it a string that can be parsed. Always use digits if possible, and you did not even specify a year.
The format yyyy-mm-dd would probably work best, as it is (both to humans and to computers) totally un-ambiguous. So try it using
DateAdd("d", -1, "2017-05-25")
Related
I have to make a report that will execute automatically several times, every day, with different settings. The report selects records between two dates. Now, the client wants to be free to define, in a text or excel file, the dates that will run each report. For example, every day I want to run the report for that day, and for that same day the previous year, and for the same day the previous week, and for the previous week, and for the next month of the previous year. Then on the first of every month, the whole previous month, etc. I think you get the gist.
My question is: Is there any established way of doing this? Some text encoding for offsets of dates? I've looked and nothing appears. However, it doesn't seem an outlandish proposition. I suppose the situation has happened before. I wouldn't like to reinvent the wheel. If, however, there is nothing, any idea would be welcome :-)
OK, so I did it myself, no free lunch this time :-) The format I chose is a string like:
+1W,fW,-1D (That would be the next week, first day of that week, then one day before that)
Separator is comma, keys are D for day, W for week, M for month, Y for year, F for first, L for Last (all keys can be lower or upper case). The format ignores whitespace, but the last non-whitespace character must be a key. Only integer offsets allowed.
I give my first implementation of a VBA function that interprets a text offset. It seems to work, although little testing done yet.
Well, that's all, for posterity.
Public Function GetDateFromOffset(fecIni As Date, sDif As String) As Date
Dim sArr() As String, ii As Integer, fRes As Date
fRes = fecIni
sArr = Split(sDif, ",")
For ii = LBound(sArr()) To UBound(sArr())
fRes = ApplyOneOffset(fRes, sArr(ii))
Next ii
GetDateFromOffset = fRes
End Function
Public Function ApplyOneOffset(fecIni As Date, sDif As String) As Date
Const C_DAY As String = "D", C_WEEK As String = "W", C_MONTH As String = "M", C_YEAR As String = "Y"
Const C_FIRST As String = "F", C_LAST As String = "L"
Dim iDesp As Integer, sDesp As String, fRes As Date
sDesp = UCase(Right(sDif, 1))
sDif = Trim(UCase(Left(sDif, Len(sDif) - 1)))
Select Case sDesp
Case C_DAY
If (IsNumeric(sDif)) Then
fRes = DateAdd("d", CInt(sDif), fecIni)
End If
Case C_WEEK
If (sDif = C_FIRST) Then
fRes = dhFirstDayInWeek(fecIni)
ElseIf (sDif = C_LAST) Then
fRes = dhLastDayInWeek(fecIni)
ElseIf (IsNumeric(sDif)) Then
fRes = DateAdd("ww", CInt(sDif), fecIni)
End If
Case C_MONTH
If (sDif = C_FIRST) Then
fRes = dhFirstDayInMonth(fecIni)
ElseIf (sDif = C_LAST) Then
fRes = dhLastDayInMonth(fecIni)
ElseIf (IsNumeric(sDif)) Then
fRes = DateAdd("m", CInt(sDif), fecIni)
End If
Case C_YEAR
If (sDif = C_FIRST) Then
fRes = DateSerial(YEAR(fecIni), 1, 1)
ElseIf (sDif = C_LAST) Then
fRes = DateSerial(YEAR(fecIni), 31, 12)
ElseIf (IsNumeric(sDif)) Then
fRes = DateAdd("yyyy", CInt(sDif), fecIni)
End If
Case Else
fRes = fecIni
End Select
ApplyOneOffset = fRes
End Function
I'm relatively new to VB6 and I've just been given an assignment where I have a date - for example '4/12/2016' - from this date, i'm trying to find out the day that it is. So let's say it's a wednesday. Now from this day, I'm trying to determine the dates for the week [sun(startdate) - sat(enddate)). How would I go about doing something like this?
EDIT: I have a pretty good idea about finding out the date for sunday and saturday, since I can simply do something along the lines...
dim dateStart,dateend as date
Ex of date given to me = '4/12/2016'
Dim dateDay as variant
dateDay = whatever I get here - i'm assuming that a date will return a number for whatever day it is ???? Not sure
Select Case dateDay
case 1 -Monday?
dateStart=dateadd("d",-1,'4/12/2016)
dateEnd = dateadd("d",6, '4/12/2016)
case 2 -Tuesday?
datestart = dateadd("d",-2,'4/12/2016)
dateend = dateadd("d",5,'4/12/2016)
End Select
Basically do the SELECT statement for all cases. Am I on the right track?
This code:
Debug.Print Format(DatePart("w", Now), "dddd")
will print whatever day of the week it is now to the Immediate window. If you want the abbreviated day of week, use "ddd" for the format.
Now, this code:
Dim DOW As String
Select Case DatePart("w", Now)
Case vbSunday
DOW = "Sunday"
Case vbMonday
DOW = "Monday"
Case vbTuesday
DOW = "Tuesday"
Case vbWednesday
DOW = "Wednesday"
Case vbThursday
DOW = "Thursday"
Case vbFriday
DOW = "Friday"
Case vbSaturday
DOW = "Saturday"
End Select
Debug.Print DOW
will do the same thing. However, it shows you how to evaluate programmatically which day of the week you're dealing with, by using vbSunday, vbMonday, etc. That should give you what you need to get started on your Select statement. To use your example, DatePart("w", "4/12/2016") evaluates to 3, or vbTuesday.
VB6 reference documentation is here, and rather well hidden I might add. Look up Format and DatePart to get familiar with other options.
EDIT: As MarkL points out, the Weekday function is available in VB6 (I thought it wasn't), and is simpler (one less argument) than using DatePart. This code:
Debug.Print Format(Weekday(Now), "dddd")
will also print whatever day of the week it is to the immediate window. jac has also provided a link to the Weekday function in the comments above.
You can try below codes, The code will return name of the day.
txtDateTime.Text = WeekdayName(Weekday(Now))
txtDateTime.Text = WeekdayName(Weekday(12 / 30 / 1995))
txtDateTime.Text = WeekdayName(Weekday(Date))
I'm having a hard time trying to gather data from an Oracle DB. I've managed to get the connection going, so the problem lies within the query. At the moment the query dont return anything, and neither VBA complains about it.
Here's the code:
Sub Connect_XXXX()
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim rs As New ADODB.Recordset
Set rs = New ADODB.Recordset
Dim myQuery As ADODB.Command
Set myQuery = New ADODB.Command
conn.Open "Provider=OraOLEDB.Oracle;" & _
"Data Source=XXXX;" & _
"User Id=YYYY;" & _
"Password=ZZZZ"
myQuery.ActiveConnection = conn
myQuery.CommandText = "SELECT sta.index_id, sta.index_action as Action, sta.ticker, sta.company, sta.announcement_date as A_Date, sta.announcement_time as A_Time, " & _
"sta.effective_date as E_Date, dyn.index_supply_demand as BS_Shares, dyn.net_index_supply_demand as Net_BS_Shares, dyn.est_funding_trade as BS_Value, " & _
"dyn.trade_adv_perc/100 as Days_to_Trade, dyn.pre_index_weight/100 as Wgt_Old, dyn.post_index_weight/100 as Wgt_New, dyn.net_index_weight/100 as Wgt_Chg, " & _
"dyn.pre_est_index_holdings as Index_Hldgs_Old, dyn.post_est_index_holdings as Index_Hldgs_New, dyn.net_est_index_holdings as Index_Hldgs_Chg, sta.index_action_details as Details " & _
"FROM index_analysis.eq_index_actions_dyn dyn, index_analysis.eq_index_actions_static sta " & _
"WHERE (sta.action_id = dyn.action_id) AND (sta.announcement_date=dyn.price_date) AND (sta.announcement_date >= '01-January-2015') AND (sta.announcement_date <= '30-January-2015') " & _
"ORDER by sta.index_id,sta.announcement_date"
Set rs = myQuery.Execute
Sheets("Sheet1").Range("A1").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
I've played around with the query a lot, and I've been able to get some results by removing some of the AND statements after the WHERE and trying with fewer fields on the SELECT statement, but I need them all in order for this results to work for me. The weird thing is that if I run the same query in a problem like Oracle Sql Developer (after connecting to the DB) it shows the results that I want. I could really use some help, Thanks!
If you are going to hard-code the date range, assuming announcement_date is a date, you'd want to compare against dates, not strings. You can use to_date with an explicit format mask to convert a string to a date,
sta.announcement_date >= to_date( '01-January-2015', 'DD-Month-YYYY')
or you can use a date literal which always has the format YYYY-MM-DD
sta.announcement_date >= date '2015-01-01'
My guess is that your code seems to work in SQL Developer because you happen to have configured your NLS_DATE_FORMAT to be 'DD-Month-YYYY' in SQL Developer.
In reality, you should really be using bind variables rather than hard-coding things like the date range. Assuming you bind a date value, the conversion (if any) from a string to a date would happen in VB and wouldn't depend on your session's NLS settings. There are also performance and security reasons to prefer bind variables.
I have a function in my VBA code which sets a specific Date format for a textbox.
This is my code to verify the Date is in the correct format:
Function CheckDate(DateStg As String) As Boolean
If DateStg = "" Then
' Accept an empty value in case user has accidentally moved to a new row
CheckDate = True
lblMessage.Caption = ""
Exit Function
End If
If IsDate(DateStg) Then
CheckDate = True
lblMessage.Caption = ""
Else
CheckDate = False
lblMessage.Caption = "Sorry I am unable to recognise " & DateStg & " as a date."
End If
End Function
In addition to checking if the date in the textbox is an actual date, I need to verify that the textbox date is not less than the current date minus 1 month, and. Also, I would like to verify that the date is not more than the current date plus 1 year.
So:
DateStg > Today - 1 month
DateStg < Today + 1 year
Thanks for your help in advance.
You have a few functions you can use:
''Assume date is not good
DateOK=False
If IsDate(DateStg) Then
If DateStg > dateAdd("m",-1,Date()) _
And DateStg < dateAdd("m",12,Date()) Then
''Date is good
DateOK=True
End If
End if
For the most part, textboxes can be set to only accept dates and you can set validation rules to check the range, so code may not be necessary.
If you just want to check the date, you can use the DateAdd-function to get the dates to compare:
'Subtract a month from today and return it as a string
Format(DateAdd("m", -1, Now), "yyyy-mm-dd")
'Add a year to today and return it as a string
Format(DateAdd("yyyy", 1, Now), "yyyy-mm-dd")
I am trying to use code to filter a spreadsheet dynamically, based on the current date.
I am storing the date I need to filter on as "CurrDay" and I'm attempting to recall that stored date back into my filter algorithm. It is not working and I need to figure out how to do this to finish up this code. Everytime I run the code it returns the CurrDay name in the filter instead of the date stored under the CurrDay variable.
I'm missing something here and I need some direction. Any help is appreciated.
CODE:
Sub Finishing_A59_Filter()
'
' Finishing_A59_Filter Macro
' This macro will activate the A59 and Filter it properly for standard orders
'
'This macro does not include the VMI's and APS orders in the code
'
'
Dim Currday As Date
Currday = Date + 7
UName = Application.UserName
Workbooks.Open Filename:="G:\Copy Modified A59 5-19-2009.xlsm", UpdateLinks _
:=0
Range("M2").Select
ActiveCell.Value = Currday
Columns("Q:Q").Select
Selection.NumberFormat = "mm/d/yyyy"
' Filter the sheet to remove VMI's and APS orders
ActiveSheet.Range("$A$3:$AA$2941").AutoFilter Field:=23, Criteria1:=Array( _
"01", "04", "06", "08", "09", "10", "15", "25", "="), Operator:=xlFilterValues
' Set the proper date range for the sheet - This needs to be seven days beyond the current date
ActiveSheet.Range("$A$3:$AA$2941").AutoFilter Field:=17, Criteria1:= _
"<=Currday", Operator:=xlAnd
You need to concatenate the variable with the criteria string.
ActiveSheet.UsedRange.AutoFilter Field:=17, Criteria1:= _
"<=" & Currday, Operator:=xlAnd
Also, it's better to use "UsedRange" instead of making up a big range because it doesn't work if your data extends past your arbitrary range and is a waste of resources if it doesn't.