Nesting the Format Function


Written By TheVBProgramer.


In general, any VB expression can contain nested functions (i.e., one function within another). For example, in some of our "Test It" projects, we used the following code to first get the user's input as a string (using the InputBox function), then converted the result to a number using the Val function:

strUserInput = InputBox("Please enter a number:")

dblTestNumber = Val(strUserInput)


These two steps could have been combined into one statement by nesting the InputBox function within the Val function:


dblTestNumber = Val(InputBox("Please enter a number:"))


Here, the InputBox function executes first and stores the user's input in a temporary string variable (there is no need for the "strUserInput" variable in this case). The Val function then converts the temporary string variable to a number and stores it in the dblTestNumber variable.



Nesting the Format$ Function to Right-Justify Numbers


When the Format$ function is used to format a number, the result of the formatting operation is a string containing the formatted number left-justified. This is fine if the number does not need to be "lined up" with other numbers in a columnar display. But if the numbers do need to be lined up, right-justification would be called for.


To right-justify a formatted number, you can use syntax like this:


Format$(Format$(dblTestNumber, "Standard"), "@@@@@@@@@@@@")


In the example above, the inner Format$ function would first format the number using the Standard format (and the result be stored in a temporary string where the data would be left-justified). Then the outer Format$ function would right-justify that first result in a field of 12 characters (hence the 12 "@"s).


To demonstrate nested formats, set up another "Try It" project, and place the following code in the cmdTryIt_Click event:


Private Sub cmdTryIt_Click()


Dim dblTestNumber As Double


dblTestNumber = Val(InputBox("Please enter a number:"))


Print "Input: "; dblTestNumber; _

Tab(25); _

Format$(dblTestNumber, "Standard"); _

Tab(40); _

Format$(Format$(dblTestNumber, "Standard"), "@@@@@@@@@@@@")


End Sub



Run the project and repeatedly click the "Try It" button and enter a number in the input box. As the form begins to fill up, you'll see that the middle column will display the numbers left-justified, whereas the last column will display the number right-justified. A screen-shot of a sample run is shown below:






Download the VB project code for the example above here.

If you enjoyed this post, subscribe for updates (it's free)

Saving the progs

how can i save the programs i make so that i can open them up on my friends computer as programs...without having to start vb6 to open it up???


Try saving it as an exeucutable (EXE) file and then it should be possible to run it as lon as all the elements are there.