Enter date into function without quotes, return date - vba

I'm trying to write a function of this form:
Function cont(requestdate As Date)
cont = requestdate
End Function
Unfortunately, when I enter =cont(12/12/2012) into a cell, I do not get my date back. I get a very small number, which I think equals 12 divided by 12 divided by 2012. How can I get this to give me back the date? I do not want the user to have to enter =cont("12/12/2012").
I've attempted to google for an answer, unfortunately, I have not found anything helpful. Please let me know if my vocabulary is correct.
Let's say my user pulled a report with 3 columns, a, b and c. a has beginning of quarter balances, b has end of quarter balances and c has a first and last name. I want my user to put in column d: =cont(a1,b1,c1,12/12/2012) and make it create something like:
BOQ IS 1200, EOQ IS 1300, NAME IS EDDARD STARK, DATE IS 12/12/2012
So we could load this into a database. I apologize for the lack of info the first time around. To be honest, this function wouldn't save me a ton of time. I'm just trying to learn VBA, and thought this would be a good exercise... Then I got stuck.

Hard to tell what you are really trying to accomplish.
Function cont(requestdate As String) As String
cont = Format(Replace(requestdate, ".", "/"), "'mm_dd_YYYY")
End Function
This code will take a string that Excel does not recognize as a number e.g. 12.12.12 and formats it (about the only useful thing I can think of for this UDF) and return it as a string (that is not a number or date) to a cell that is formatted as text.
You can get as fancy as you like in processing the string entered and formatting the string returned - just that BOTH can never be a number or a date (or anything else Excel recognizes.)

There is no way to do exactly what you're trying to do. I will try to explain why.
You might think that because your function requires a Date argument, that this somehow forces or should force that 12/12/2012 to be treated as a Date. And it is treated as a Date — but only after it's evaluated (only if the evaluated expression cannot be interpreted as a Date, then you will get an error).
Why does Excel evaluate this before the function receives it?
Without requiring string qualifiers, how could the application possibly know what type of data you intended, or whether you intended for that to be evaluated? It could not possibly know, so there would be chaos.
Perhaps this is best illustrated by example. Using your function:
=Cont(1/1/0000) should raise an error.
Or consider a very simple formula:
=1/2
Should this formula return .5 (double) or January 2 (date) or should it return "1/2" (string literal)? Ultimately, it has to do one of these, and do that one thing consistently, and the one thing that Excel will do in this case is to evaluate the expression.
TL;DR
Your problem is that unqualified expression will be evaluated before being passed, and this is done to avoid confusion or ambiguity (per examples).

Here is my method for allowing quick date entry into a User Defined Function without wrapping the date in quotes:
Function cont(requestdate As Double) As Date
cont = CDate((Mid(Application.Caller.Formula, 7, 10)))
End Function
The UDF call lines up with the OP's initial request:
=cont(12/12/2012)
I believe that this method would adapt just fine for the OP's more complex ask, but suggest moving the date to the beginning of the call:
=cont(12/12/2012,a1,b1,c1)
I fully expect that this method can be optimized for both speed and flexibility. Working on a project now that might require me to further dig into the speed piece, but it suits my needs in the meantime. Will update if anything useful turns up.
Brief Explanation
Application.Caller returns a Range containing the cell that called the UDF. (See Caveat #2)
Mid returns part of a string (the formula from the range that called the UDF in this case) starting at the specified character count (7) of the specified length (10).
CDate may not actually be necessary, but forces the value into date format if possible.
Caveats
This does require use of the full dd/mm/yyyy (1/1/2012 would fail) but pleasantly still works with my preferred yyyy/mm/dd format as well as covering some other delimiters. dd-mm-yyyy or dd+mm+yyyy would work, but dd.mm.yyyy will not because excel does not recognize it as a valid number.
Additional work would be necessary for this to function as part of a multi-cell array formula because Application.Caller returns a range containing all of the associated cells in that case.
There is no error handling, and =cont(123) or =cont(derp) (basically anything not dd/mm/yyy) will naturally fail.
Disclaimers
A quick note to the folks who are questioning the wisdom of a UDF here: I've got a big grid of items and their associated tasks. With no arguments, my UDF calculates due dates based on a number of item and task parameters. When the optional date is included, the UDF returns a delta between the actual date and what was calculated. I use this delta to monitor and calibrate my calculated due dates.
All of this can absolutely be performed without the UDF, but bulk entry would be considerably more challenging to say the least.
Removing the need for quotes sets my data entry up such that loading =cont( into the clipboard allows my left hand to F2/ctrl-v/tab while my right hand furiously enters dates on the numpad without need to frequently (and awkwardly) shift left-hand position for a shift+'.

Related

I cannot understand why "in" doesn't work correctly

sp01 is dataframe which contains S&P 500 index. And I have a dataframe,interest, which contains daily interest rate. The two data started from same date, but their size were not same. It's error.
I want to get exact same date, so tried to check every date using "in" function. But "in" function doesn't work well. This is code :
print(sp01.Date[0], type(sp01.Date[0]) )
->1976-06-01, str
print(interest.DATE[0], type(interest.DATE[0]) )
->1976-06-01, str
print(sp01.Date[0] in interest.DATE)
->False
I can never understand why the result becomes False.
Of course, first date of sp01 and interest is totally same,
I checked it too by typing code. So, True should be come out, but False came out. I got mad!!!please Help me.
I solved it! the problem is that "in" function does not work for pandas series data. Those two data are pandas series, so I have to change one of them to list

How to display comparisons with set expression?

My dataset has WeekEndingDate and Sales. I am displaying a straight table with all the selected data but I need to have another table showing the following:
Sales (other columns...)
First week : 1,000
Last week : 1,350
Difference : 350
Difference %: 35%
My questions:
a) Can I have the above in one chart/table, or I need 4 different charts showing columns filtered by set expressions?
b) My strategy is having 2 variables (vMinWeek and vMaxWeek), and using them in set expressions. Is that the best route?
c) My set expressions (below) are not working - they sum the whole data set. Would you please help me understanding why?
=max ({$<WeekEndingDate={'$(vMinWeek)'}>} Sales)
Thank you for your help!
Mara
I think the reason your set isn't working is that your WeekEnd date is formatted as a date and your variable is formatted as a number.
The trick with Set Analysis is always to think what you would have to type in a list box to get to your answer. So even though QlikView stores WeekEnd 2014/08/18 as 41869 you can't type 41869 in the WeekEnd list box and get back that date. So I would make your variables of the form =date(min(WeekEnd)).
The second part of your question; getting the table you want. I would do like this. I make a loose table with the dimension values, dual is so that it sorts correctly in the chart we are going to build.
load dual(D,N) as DIM inline [
D,N
First Week,1
Last Week,2
Difference,3
Dif %,4
];
I like defining my variables in the script as well, so I would do this.
set vFirstWeek='=date(min(WeekEnd))';
set vLastWeek='=date(max(WeekEnd))';`
Then when building the straight table we use the dimension as DIM but because DIM isn't connected to anything we have to do some work to get it to display values that fit those dimension values. The num(,'# ##0') is just to format the % differently from the sums. For this to work the number format in the Number tab of the chart must be set to Expression Default.
if(DIM='First Week',num(sum({<WeekEnd={'$(vFirstWeek)'}>} Sales),'# ##0'),
if(DIM='Last Week',num(sum({<WeekEnd={'$(vLastWeek)'}>} Sales),'# ##0'),
if(DIM='Difference',num(sum({<WeekEnd={'$(vFirstWeek)'}>} Sales)-sum({<WeekEnd={'$(vLastWeek)'}>} Sales),'# ##0'),
if(DIM='Dif %',num((sum({<WeekEnd={'$(vFirstWeek)'}>} Sales)-sum({<WeekEnd={'$(vLastWeek)'}>} Sales))/sum({<WeekEnd={'$(vLastWeek)'}>} Sales),'0.00%')))))

Constructing a recursive compare with SQL

This is an ugly one. I wish I wasn't having to ask this question, but the project is already built such that we are handling heavy loads of validations in the database. Essentially, I'm trying to build a function that will take two stacks of data, weave them together with an unknown batch of operations or comparators, and produce a long string.
Yes, that was phrased very poorly, so I'm going to give an example. I have a form that can have multiple iterations of itself. For some reason, the system wants to know if the entered start date on any of these forms is equal to the entered end date on any of these forms. Unfortunately, due to the way the system is designed, everything is stored as a string, so I have to format it as a date first, before I can compare. Below is pseudo code, so please don't correct me on my syntax
Input data:
'logFormValidation("to_date(#) == to_date(^)"
, formname.control1name, formname.control2name)'
Now, as I mentioned, there are multiple iterations of this form, and I need to loop build a fully recursive comparison (note: it may not always be typical boolean comparisons, it could be internally called functions as well, so .In or anything like that won't work.) In the end, I need to get it into a format like below so the validation parser can read it.
OR(to_date(formname.control1name.1) == to_date(formname.control2name.1)
,to_date(formname.control1name.2) == to_date(formname.control2name.1)
,to_date(formname.control1name.3) == to_date(formname.control2name.1)
,to_date(formname.control1name.1) == to_date(formname.control2name.2)
:
:
,to_date(formname.control1name.n) == to_date(formname.control2name.n))
Yeah, it's ugly...but given the way our validation parser works, I don't have much of a choice. Any input on how this might be accomplished? I'm hoping for something more efficient than a double recursive loop, but don't have any ideas beyond that
Okay, seeing as my question is apparently terribly unclear, I'm going to add some more info. I don't know what comparison I will be performing on the items, I'm just trying to reformat the data into something useable for ANY given function. If I were to do this outside the database, it'd look something like this. Note: Pseudocode. '#' is the place marker in a function for vals1, '^' is a place marker for vals2.
function dynamicRecursiveValidation(string functionStr, strArray vals1, strArray vals2){
string finalFunction = "OR("
foreach(i in vals1){
foreach(j in vals2){
finalFunction += functionStr.replace('#', i).replace('^', j) + ",";
}
}
finalFunction.substring(0, finalFunction.length - 1); //to remove last comma
finalFunction += ")";
return finalFunction;
}
That is all I'm trying to accomplish. Take any given comparator and two arrays, and create a string that contains every possible combination. Given the substitution characters I listed above, below is a list of possible added operations
# > ^
to_date(#) == to_date(^)
someFunction(#, ^)
# * 2 - 3 <= ^ / 4
All I'm trying to do is produce the string that I will later execute, and I'm trying to do it without having to kill the server in a recursive loop
I don't have a solution code for this but you can algorithmically do the following
Create a temp table (start_date, end_date, formid) and populate it with every date from any existing form
Get the start_date from the form and simply:
SELECT end_date, form_id FROM temp_table WHERE end_date = <start date to check>
For the reverse
SELECT start_date, form_id FROM temp_table WHERE start_date = <end date to check>
If the database is available why not let it do all the heavy lifting.
I ended up performing a cross product of the data, and looping through the results. It wasn't the sort of solution I really wanted, but it worked.

Reporting Services - handling an empty date?

Hey, I have a report parameter which looks like this: 01.01.2009 00:00:00
Its a date (as string), as you might have guessed :). The problem is, this param can be an empty string as well. So I tried those expressions:
=IIf(IsDate(Parameters!DateTo.Value), CDate(Parameters!DateTo.Value), "")
=IIf(Len(Parameters!DateTo.Value) > 0, CDate(Parameters!DateTo.Value), "")
Both dont work and the value for the textfield where I print the expressions result is always #Error. As soon as I remove the CDate stuff, it works, but I have to use it. IS there another way to achieve that? What I want is to display nothing if its not a date or the date (format dd.mm.yyyy) if its a date.
Ideas?
Thanks :)
All arguments to the IIf are evaluated, which results in your error, since the CDate will fail for an empty string.
You can get around this by just writting a function along these lines, using a standard if statement:
Function FormatDate(ByVal s As String) As String
If (s <> "") Then
Return CDate(s).ToString()
Else
Return ""
End If
End Function
Then call it with: =Code.FormatDate(Parameters!DateTo.Value)
First, fix your database to properly store dates rather than doing these workarounds. You probably have bad data in there as well (Feb 30 2010 for example or my favorite, ASAP). Truly there is no excuse for not fixing this at the database level where it needs to be fixed except if this is vendor provided software that you can't change (I would yell at them though, well notify them really, and ask them to fix their data model or go to a new product designed by someone who knows what they are doing. A vendor who can't use dates properly is likely to have software that is very poor all around).
In the query that you use to select the infomation, have you considered just converting all non-dates to null?

Failure to Pass Arguments to a UDF in VBA for Excel 2007

I have a complex iterative spreadsheet in which I want to use a UDF to calculate the heat transfer coefficient of a heat exchanger. The function has 5 arguments (2 strings and 3 doubles). The strings and 1 double pass just fine. The remaining two don't seem to go through at all. A watch on problematic arguments shows them to be equal to zero. I tried redefining the arguments as variants, and then I can find the value I want in the "value2" field. However, as soon as I try to access it (via varName.Value2) it disappears (the watch suddenly lists the field as "Empty").
The cells passed into the function for the problematic arguments are heavily dependent on the rest of the spreadsheet, and their value changes almost every iteration.
Has anyone seen this before and know of a workaround?
I use UDFs with +6 input variables (the standard types as well as variants), and I have noticed (this is my interpreation of what happens) that sometimes the excel calc engine tries to trigger the UDF before all the input values become calced and available. From the debug view this is seen as the function making "false starts" and stopping to execute mid-procedure (thread is lost) so debugging-wise it shows a strange behaviour.
However, when written into a cell the function still calculates and returns correctly.