is it possible in vb.net to declare a variable as a string if it has already been declared as a date? - vb.net

I am declaring this variable in my vb.net application:
Dim invoice_due_date As Date = get_invoice_due_date(InvoiceDate.Text, customer_sequence)
i want to have an if statement that will declare this variable again as a String rather than a Date
is this possible?
i tried putting the If below but it tells me it hides a variable in an enclosing block

Read up (google) on "variable scope". What you want is not only not possible, it would be bad practice.
You either declare a new variable (different name) with a different data type and load the contents of invoice_due_date into it or, as #Plutonix already suggested, use .ToString()

Related

Variable in a form won't keep its value after being used in the call to another form

I have a form with a variable in it called "VigilTable." This variable gets its value from the calling string OpenArgs property.
Among other things, I use this variable in the call string when opening other forms.
But it only works the first call.
MsgBox VigilTable before the call will always show "Spring2022" or whatever on the first call but always comes up blank on succeeding calls (and I get "invalid use of NULL" when the called form attempts to extract the value from OpenArgs). The variable is dimmed as String in the General section of the form's VBA code.
So what's happening here? And can I fix it?
Thanks.
Ok, so you delcared a variable at the form level (code module) for that given form.
and we assume that say on form load, you set this varible to the OpenArgs of the form on form load.
So, say like this:
Option Compare Database
Option Explicit
Public MyTest As String
Private Sub Form_Load()
MyTest = Me.OpenArgs
End Sub
Well, I can't say having a variable helps all that much, since any and all code in that form can use me.OpenArgs.
but, do keep in mind the following:
ONLY VBA code in the form can freely use that variable. It is NOT global to the applcation, but only code in the given form.
However, other VBA code outside of the form can in fact use this variable. But ONLY as long as the form is open.
So, in the forms code, you can go;
MsgBox MyTest
But, for VBA outside of the form, then you can get use of the value like this:
Msgbox forms!cityTest.MyTest
However, do keep in mind that any un-handled error will (and does) blow out all global and local variables. So, maybe you have a un-handled error.
Of course if you compile (and deploy) a compiled accDB->accDE, then any errors does NOT re-set these local and global variables.
but, for the most part, that "value" should persist ONLY as long as the form is open, and if you close that form, then of course the values and variables for that form will go out of scope (not exist).
Now, you could consider moving the variable declare to a standard code module, and then it would be really global in nature, but for the most part, such code is not recommended, since it hard to debug, and such code is not very modular, or even easy to maintain over time.
So, this suggests that some error in VBA code is occurring, and when that does occur, then all such variables are re-set (but, the noted exception is if you compile down to an accDE - and any and all variables will thus persist - and even persist their values when VBA errors are encountered.
For a string variable, a more robust solution not influenced by any error, should be writing/reading in/from Registry. You can use the, let as say, variable (the string from Registry) from any workbook/application able to read Registry.
Declare some Public constants on top of a standard module (in the declarations area):
Public Const MyApp As String = "ExcelVar"
Public Const Sett As String = "Settings"
Public Const VigilTable As String = "VT"
Then, save the variable value from any module/form:
SaveSetting MyApp, Sett, VigilTable , "Spring2022" 'Save the string in Regisgtry
It can be read in the next way:
Dim myVal as String
myVal = GetSetting(MyApp, Sett, VigilTable , "No value") 'read the Registry
If myVal = "No value" Then MsgBox "Nothing recorded in Registry, yet": Exit Sub
Debug.print myVal
Actually, this proved not to be the the answer at all.
It was suggested that I declare my variables as constants in the Standard module but I declared them as variables. It appeared at first to work, at least through one entire session, then it ceased to work and I don't know why.
If I declare as constants instead, will I still be able to change them at-will? That matters because I re-use them with different values at different times.
I didn't do constants but declaring VigilName in the Standard module and deleting all other declarations of it fixed both problems.
While I was at it I declared several other variables that are as generally used and deleted all other declarations of them as well so that at least they'll be consistently used throughout (probably save me some troubleshooting later.
Thanks to all!

Variable declaration placement guidelines in VBScript

Is there any rule for placement of variable declaration in VBScript, like if it should always be declared in the beginning? Or can I declare the variable while using it? Which one is more efficient?
Let's try with a simple code, with Option Explicit included so VBScript parser requests that all the variables used in the code are declared
Option Explicit
WScript.Echo TypeName( data )
WScript.Echo TypeName( MY_DATA )
Dim data : data = 10
Const MY_DATA = 10
WScript.Echo TypeName( data )
WScript.Echo TypeName( MY_DATA )
When executed it will ouptut
Empty
Integer
Integer
Integer
That is
The first access to data does not generate any error. Variable declaration (the Dim statement) is hoisted. If the variable is declared inside the same (or outer) scope where it will be used then there will not be any problem.
But the first output is Empty. Only the declaration is hoisted, not the value assignment that is not executed until the line containing it is reached.
That does not apply to constant declaration. Its value is replaced in code where it is used but the real declaration is delayed until the const line is reached (read here).
As long as the variables/constants can be reached (they are declared in the same or outer scope) it is irrelevant (to the VBScript parser/engine) where you place the declaration.
But, of course, you or others will have to maintain the code. Being able to put the variables anywhere doesn't mean you should do something like the previous code (please, don't). It is a lot easier to read/maintain the code if variable declaration is done before initialization/usage. The exact way of doing it just depends on coding style.

VBA - Compile Error: Expected Function or Variable

To start, I am not a programmer. Im just someone trying to make a document that has an "invoice" number that increases on the document that goes up every time I print the document. I found a macro code online but I keep getting the
Compile error
I'll attach a snap shot of what im getting with the piece that keeps screwing up high lighted.
Is there something I'm doing wrong?
To expand on braX's answer...
That's the syntax for assigning the return value of a Function or Property Get member - namely, you are assigning to the procedure's identifier:
Public Function GetTotallyRandomNumber() As Long
GetTotallyRandomNumber = 4
End Function
Seems you mean to have a local variable named SerialNumber, however VBA already knows this identifier as the name of a Sub procedure named SerialNumber, and because a Sub procedure doesn't return anything, it can't legally be assigned like this.
Declare a local variable inside the procedure's scope, before the illegal assignment:
Dim SerialNumber As String
SerialNumber = System.PrivateProfileString(...)
And then your code will work... however I wouldn't recommend using the exact same name as the procedure.
My recommendation would be to name the local variable SerialNumber, and to rename the Sub procedure so that its name starts with a verb. Procedures do something, they're actions: find a meaningful name that describes what it does, and go with that.
Naming is hard though - if you can't find a simple name that describes what your procedure does, it's probably because it's doing too many things. Split it up into smaller, more focused procedures.
Public Sub PrintActiveDocumentAndAddSerialNumberBookmark()
You are treating a Function like a Subroutine. Subroutines do not return values.
If you want the routine to return a value, then change Sub to Function (at the top)
If you are not wanting it to return anything, then choose a different variable name instead of SerialNumber, or change the name of the Subroutine.
You cannot use a variable name that is the same as the name of the Subroutine.

Excel 2010 VBA: Invalid procedure call when adding data field to pivot table

I want to create multiple pivot tables by encapsulating the complexity into functions and procedures (I did already manage to create pivots with VBA, but one module for each pivot, meaning lots of repetitive code...)
I managed to create procedures and functions to create the pivot, add a filter, and a row field. But when it comes to adding a data field, I get an invalid procedure call; the strange thing however is that I get that error only when I use variables to pass info: looking at the line prodicung the error, the first line works perfectly fine, whereas I cannot get the second line running (the variables contain the correct values):
pivotName.addDataField pivotName.PivotFields("sdID"), "SD ID number", xlCount 'works fine
pivotName.addDataField pivotName.PivotFields(fieldName), fieldDescription, calcMethod 'produces Invalid procedure call error
As I am running out of ideas, any help would be highly appreciated!
Thank you very much,
Alexander
The reason for the error is due to calcMethod being declared earlier in the code as a string.
The .addDataField method accepts the following parameters:
.AddDataField(Field, Caption, Function)
The parameter Function is of the XLConsolidationFunction enum and therefore should be declared and assigned like below:
Dim calcMethod As XlConsolidationFunction
calcMethod = xlCount
Once declared and assigned as above, you can use it within your method in the following way where fieldName and fieldDescription are both strings:
pivotName.addDataField pivotName.PivotFields(fieldName), fieldDescription, calcMethod
As you can see in the comment from Gareth, the problem was to declare calcMethod (optional function) as string, not as XLConsolidatedFunction.
Thank you once again!

VBA assigning new object to variable?

I'm trying create new object from a module class in VBA, and I have a small diffcult. Two line of assigning code, look like the same, but result is different.
I got a error message:
After that, I switch to use (1) instead of (2), error was fixed.
But I dont understand; Why do they have this difference?
Dim declares a variable, Set instantiates it.
So, it's a good practice to always have Dim before Set.
If you do not use Dim to declare the specific type of a variable you may subsequently change the variable to another type, for example after;
set aosh = new AOSHRatioQuery
You could mutate the variable to a string;
aosh = "A pint of milk"
As the sendAsyncRequest method expects a AOSHRatioQuery as its 2nd argument & the VBA compiler knows that it cannot guarantee that the aosh variable will actually contain an instance of that type, type safety is violated & the Type Mismatch error is raised to prevent sendAsyncRequest from receiving garbage it cannot interpret.
Explicitly typing with Dim aosh as new AOSHRatioQuery tells the compiler that aosh is guaranteed to always be AOSHRatioQuery instance or Nothing (attempting to assign it to another type will raise an error) so it can be passed safely.
In VBA, you have to declare variables using the Dim keyword, and then defining their data types with the As keyword. That's just how its syntax works. As a general form:
Dim <variableName> As <dataType>