udf to replace the datediff function value error - user-defined-functions

I am trying to make a udf to replace the datediff function.
reason: the udf will end up in my very (close to 8192 limit) long formula.
I use the "dutch" vba therefor datediff is "datumverschil" (a long word)
I want to replace it with "dv"
but so far my dv udf is not working, and I cannot guess where the error
could be... the error says "error in value"...
this is what I have now:
Public Function dv(eerste As Date, tweede As Date, str As String) As Variant
dv = DateDiff(str, eerste, tweede)
End Function
who sees the error :) ? have a great sunday and thank you :) !

Im not sure about the language you are using, but normally each argument in a function has to go in order. Maybe this is your error?
In your code you have:
Public Function dv(eerste As Date, tweede As Date, str As String) As Variant
As you can probably see here, eerste goes first, tweede goes second, and str goes last.
So to pass the arguments through properly you would have to do:
dv(eerste, tweede, str)
Hope this solves your issue and have a nice day! :)
Edit:
I also noticed your function and your variable are named the same?
Again im not sure what language you are using, but it seems assigning DateDiff to the dv variable, you would be overwriting the function?
Perhaps you meant DateDiff = dv(eerste, tweede, str)

Related

Is it possible to get FORMAT to ignore undefined format directives?

I wonder if it is possible to tell FORMAT to ignore undefined format directives. I have looked at the pages for FORMAT in the CLHS but I don't see anything.
What I am trying to do is to get FORMAT to ignore ~m in a format string and just output ~m instead of trying to replace it with something. My plan is that at that point I will call another function which knows what to do with with ~m.
I guess a related question is then, is there a way to define a function to handle a format directive which is otherwise not defined?
In anticipation of some questions. (1) I guess a workaround would be to substitute a placeholder for ~m, and then substitute it back in afterwards and keep going. I guess I'll do that if all else fails. (2) I guess another general strategy would be to call the other function first, to handle ~m, then call FORMAT on the result. Unfortunately that other function recognizes some of the same directives, and barfs on others; it doesn't recognize only ~m and ignore everything else.
You can define your own format directive with ~/name/, where name is the name of the function which is called. In your case you would have:
(format t "~/m/" 1)
(defun m (stream n colon-mod at-mod)
(format stream "~a" n)) ; or do something else with n
You still need to change the control string, but you can add a preprocessing step where "~m" is replaced by "~/m/".
I don't think there is a way of doing that portably (implementations may let you do all sorts of magic). I'd write a quote-weird-tildes and dequote-weird-tildes pair of functions and then write code like:
(defun format/qw (control &rest args)
(declare (dynamic-extent args)
(type string control)) ;can't be a function
(dequote-weird-tildes
(apply #'format nil (quote-weird-tildes control) args)))
Now you have a function which looks like (format nil ...) and is no harder to use than that. For extra value the quoting and dequoting functions should not cons a string if they don't have to.
From http://www.lispworks.com/documentation/lw50/CLHS/Body/22_c.htm
The control-string argument to format is actually a format control.
That is, it can be either a format string or a function, for example a
function returned by the formatter macro.
So you can do:
(defmacro frmt (control-string)
(let ((str (cl-ppcre:regex-replace-all "~m" control-string "~~m")))
`(formatter ,str)))
Now:
(format t (frmt "~m~A") 1)
outputs:
~m1
NIL
This way you don't have to modify the control string directly.
You do have to modify the call to format to include frmt.

Too many arguments have been given to this function

I am getting the error, stated in the title, with the following code:
ToText (Split ({?CutOffDate},"-") [2]),ToText (Split ({?CutOffDate},"-") [1]))
Please help fresh programmer find the problem!
Check first if this is a conversion issue, using the CDate function, as in here:
ToText(CDate({aString}), "dd-MMM-yy")
Don't forget the := assignment operator
EffectiveDateTimeString := ToText(CurrentDate + CurrentTime, "dd-MM-yyyy hh:mm:ss");

What is the return type of my VBScript function?

This question is mostly out of interest to understand the functionality of VBScript better. I recognize that I can simply do some casting to know what to expect from my code, but in my situation I want to understand why casting, or any "workaround", is needed. For simplicity, here's the basic idea of my code:
variable1 = 1
Public Function findSomethingInATextString(par1, par2)
[...searching with a Do Until loop code here...]
Result = 1
If([par2 is found in par1]) Then
Result = 0
End If
Return Result
End Function
variable1 = findSomethingInATextString("Hello World", "Hello")
When I run this I get a Type Mismatch error. I don't understand why that's the case. variable1 is an integer and findSomethingInAString() returns an integer. They appear to be the same data type.
I'm working in a restricted environment where I can't do much debugging (it's painfully slow to code in this program...). So at the moment I'm unable to say what data type this is coming out as - I just know that it's apparently not integer.
After all that, and to make sure my question is clear, I'm intrigued to know what the return type of my function is (if someone happens to know), but my real question is: Why isn't the return type matching with variable1?
Use the minimal script
Return
Output
cscript 36633603.vbs
...36633603.vbs(1, 1) Microsoft VBScript runtime error: Type mismatch: 'return'
to prove to yourself, that just mentioning return in a VBScript will throw a type mismatch error.
Believe JosefZ's comment that VBScript returns function values by assigning to the function's name. Better: Read the docs (before you try to write code).
Evidence:
Function f1()
f1 = 1
End Function
WScript.Echo f1(), TypeName(f1())
Output:
cscript 36633603.vbs
1 Integer

Random number in Lua script Load Impact

I'm trying to create a random number generator in Lua. I found out that I can just use math.random(1,100) to randomize a number between 1 and 100 and that should be sufficient.
But I don't really understand how to use the randomize number as variables in the script.
Tried this but of course it didn't work.
$randomCorr = math.random(1,100);
http.request_batch({
{"POST", "https://store.thestore.com/priceAndOrder/selectProduct", headers={["Content-Type"]="application/json;charset=UTF-8"}, data="{\"ChoosenPhoneModelId\":4,\"PricePlanId\":\"phone\",\"CorrelationId\":\"$randomCorr\",\"DeliveryTime\":\"1 vecka\",\"$$hashKey\":\"006\"},\"ChoosenAmortization\":{\"AmortizationLength\":0,\"ChoosenDataPackage\":{\"Description\":\"6 GB\",\"PricePerMountInKr\":245,\"DataAmountInGb\":6,\"$$hashKey\":\"00W\"},\"ChoosenPriceplan\":{\"IsPostpaid\":true,\"Title\":\"Fastpris\",\"Description\":\"Fasta kostnader till fast pris\",\"MonthlyAmount\":0,\"AvailiableDataPackages\":null,\"SubscriptionBinding\":0,\"$$hashKey\":\"00K\"}}", auto_decompress=true},
{"GET", "https://store.thestore.com/api/checkout/getproduct?correlationId=$randomCorr", auto_decompress=true},
})
In Lua, you can not start a variable name with $. This is where your main issue is at. Once the $ is removed from your code, we can easily see how to refer to variables in Lua.
randomCorr = math.random(100)
print("The random number:", randomCorr)
randomCorr = math.random(100)
print("New Random Number:", randomCorr)
Also, concatenation does not work the way you are implying it into your Http array. You have to concatenate the value in using .. in Lua
Take a look at the following example:
ran = math.random(100)
data = "{\""..ran.."\"}"
print(data)
--{"14"}
The same logic can be implied into your code:
data="{\"ChoosenPhoneModelId\":4,\"PricePlanId\":\"phone\",\"CorrelationId\":\""..randomCorr.."\",\"DeliveryTime\":\"1 vecka\",\"$$hashKey\":\"006\"},\"ChoosenAmortization\":{\"AmortizationLength\":0,\"ChoosenDataPackage\":{\"Description\":\"6 GB\",\"PricePerMountInKr\":245,\"DataAmountInGb\":6,\"$$hashKey\":\"00W\"},\"ChoosenPriceplan\":{\"IsPostpaid\":true,\"Title\":\"Fastpris\",\"Description\":\"Fasta kostnader till fast pris\",\"MonthlyAmount\":0,\"AvailiableDataPackages\":null,\"SubscriptionBinding\":0,\"$$hashKey\":\"00K\"}}"
Or you can format the value in using one of the methods provided by the string library
Take a look at the following example:
ran = math.random(100)
data = "{%q}"
print(string.format(data,ran))
--{"59"}
The %q specifier will take whatever you put as input, and safely surround it with quotations
The same logic can be applied to your Http Data.
Here is a corrected version of the code snippet:
local randomCorr = math.random(1,100)
http.request_batch({
{"POST", "https://store.thestore.com/priceAndOrder/selectProduct", headers={["Content-Type"]="application/json;charset=UTF-8"}, data="{\"ChoosenPhoneModelId\":4,\"PricePlanId\":\"phone\",\"CorrelationId\":\"" .. randomCorr .. "\",\"DeliveryTime\":\"1 vecka\",\"$$hashKey\":\"006\"},\"ChoosenAmortization\":{\"AmortizationLength\":0,\"ChoosenDataPackage\":{\"Description\":\"6 GB\",\"PricePerMountInKr\":245,\"DataAmountInGb\":6,\"$$hashKey\":\"00W\"},\"ChoosenPriceplan\":{\"IsPostpaid\":true,\"Title\":\"Fastpris\",\"Description\":\"Fasta kostnader till fast pris\",\"MonthlyAmount\":0,\"AvailiableDataPackages\":null,\"SubscriptionBinding\":0,\"$$hashKey\":\"00K\"}}", auto_decompress=true},
{"GET", "https://store.thestore.com/api/checkout/getproduct?correlationId=" .. randomCorr, auto_decompress=true},
})
There is something called $$hashKey also, in the quoted string. Not sure if that is supposed to be referencing a variable or not. If it is, it also needs to be concatenated into the resulting string, using the .. operator (just like with the randomCorr variable).

vbscript Type mismatch error when calling function

I am running into the Type Mismatch error when I attempt to call a function I created.
Example:
Function DoThis(paramA, paramB, paramC)
If paramA = "Something" Then
DoThis = DoSomething
ElseIf paramA = "This" Then
DoThis = DoSomethingDifferent
Else
DoThis = DoThisOtherThing
End If
End Function
Dim result: result = DoThis(valueA, ValueB, ValueC)
Can anyone see what my mistake could be? Other functions are working correctly. I have double checked the spelling by actually copying and pasting the function name where I call it. I have verified that the function name is not used anywhere else, i.e., as a constant or something else.
Note that when debugging this the ValType for all arguments is vbString. Also I am never able to enter the function, so it is not like I am debugging the function, enter it and then get the type mismatch.
ty.
VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it is used. Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript.
There are some subtypes of data that a Variant can contain (e.g. Empty, Null, string, integer, object, array etc.) You can use some conversion functions to convert data from one subtype to another, if that conversion is not implicit in VBScript. Now, pay your attention to real, factual data subtype of True and vbTrue.
The True keyword (boolean literal) has a value (inner representation) equal to -1.
On the other hand, vbTrue is one of few built-in constants and, in despite of it's name, has a subtype of Integer! It's one of so-called Tristate Constants:
Constant Value Description
vbUseDefault -2 Use default from computer's regional settings.
vbTrue -1 True
vbFalse 0 False
I hope next code could make clear all above statements:
Wscript.Echo _
vbTrue, CStr( vbTrue), VarType( vbTrue), TypeName( vbTrue) , _
vbNewLine, True, CStr( True), VarType( True), TypeName( True)
However, used with If _condition_ Then ..., there are some particularities; in brief:
The Then part of the If ... statement conditionally executes groups of statements only when a single test If condition is not False, i.e. any non-zero number esteems to be true, not only -1. Therefore you are able to use whatever variable or expression (numeric or string) you choose as long as the result is numeric...
Summarizing: If _expr_ Then ... is the same as
If CBool(_expr_) Then ...
The reason why retval is retuning mismatch error because it has a numeric value and an alpha value and wsh does not like that.
A sure way to get a type mismatch error for the published code is to define DoSomething etc. as Subs (which seems probable, given the names).
I cannot explain why this was a problem, but today I reduced the function down to a simple boolean return value and I still got the type mismatch error.
So I then created a new function with the same parameters and such. When I changed the call to the new function the error goes away.
My original function with the simple boolean return:(MISMATCH ERROR)
Function IsInstalledCheck(valueToCheck, expectedValue, checkType)
IsInstalledCheck = vbFalse
End Function
My new function with the a simple return:(Works)
Function IsItemInstalled(valueToCheck, expectedValue, checkType)
IsItemInstalled = vbFalse
End Function
EDIT
Note that I had tried this with the standard True / False values as well. The solution was to simply recreated the same function with a new name and for whatever magical reason that worked. The function signature was the same, the order of variables, variable names, the test conditions, everything in the body of the new function is the same.

Resources