Calculating multi-step math in a text box. - Visual Basic - vb.net

I would like an application that I am creating in Visual Studio 2010 to be able to calculate a multi-step math problem that has been entered by the user into one whole text box.
ex. 3 * 55 / 7 ^ 2
The user would click a button, and the program would calculate the answer to the problem that they input. I was thinking something along the lines of:
Dim sngAnswer As Integer
sngAnswer = Val(Me.txtInput.Text)
But that doesn't work. Any ideas?

There is nothing included in the framework which will do this type of expression evaluation automatically.
You will likely want to use an expression parsing library to handle the math expression. NCalc and FLEE are both good options for this.

Related

How to create a program to convert unit measurements

Using Microsoft access, visual basic.
I'm having a big problem doing this task.
What I have done: Created a table on access where I have put measurements in (from meters):
mile = 10000meters, nautic mile = 1862meters, English mile=1652, kilometers = 1000 meters and all the way down to Millimeters.
What I have created for input:
1 box takes an Integer to be converted and a 1 box specified with an initial unit.
What I have created for Output:
1 box shows the Integer of result with 1 box specified the chosen unit of the output.
Can anyone please, please help me with the codes?
Honestly I'd never really noticed the CONVERT function until today but here's a quick demo of how I'd slap together a "conversion tool" in Excel.
If you want to do the same thing in Access, the premise is the same, but it will be a bit more work since you'll have to design the form from scratch instead of using a worksheet, which is kind of meant for this kind of job.
Using Excel functions in Access
Before you are able to use Excel's CONVERT function in Access, you'll need to reference the Microsoft Excel Object Library.
In Access, open any VBA Module.
GoTools > References
Check the box next to Microsoft Excel 16.0 Object Library. (The version number will vary if you have an older version of Office.)
Then you can call most Excel functions from Access VBA or queries with WorksheetFunction (the same way you would use them in Excel VBA).
For example:
MsgBox WorksheetFunction.Convert(3.7, "m", "ft")
...displays a message box with the number of feet in 3.7 metres.
The calculations will be the easy part; a couple lines of VBA in the On Change or On Exit events will trigger the calculation.
The most time-consuming part will likely be perfecting the placement and formatting of the controls on the form, which is by no means difficult (and there are several tutorials online that can provide the basics if necessary.)
Lastly, keep in mind that there are no doubt a plethora of existing conversion tools available for free download with a little Googling... (I'm confident that you're not the first person who wanted to use MS Office to convert measurements.) 😉
More Information:
Microsoft Docs : WorksheetFunction.Convert Method
Microsoft Docs : List of Worksheet Functions Available to Visual Basic
Office Support : Create a form in Access
QuackIt: Microsoft Access Tutorial
Blueclaw : Access Event Procedures
You can download the demo xlsx used above from JumpShare here.
For both comboboxes, bind them to column 2, faktorTilMeter, and set the ColumnWidths to, say: 2,542cm;0cm.
Then, assign this expression as ControlSource for your output textbox:
=TextboxInput/ComboboxFrom*ComboboxTo

In VB.net is there an option to force generation of the counter variable in the "Next" statement?

Visual Basic .net automatically inserts a "Next" statement when you enter a "For" statement; e.g., if I type:
For i as integer = 1 to 10
a Next will automatically be inserted, so that the code looks like:
For i as integer = 1 to 10
Next
It is optional to put the counter variable ("i" in the above) in the Next statement, so that it would read:
Next i
I'd really like to make this the default, as it really helps when one has nested For statements. I can't find anything in the Visual Studio settings to do this; maybe it's partly buried somewhere in Intellisense. I thought perhaps someone out there has already figured this out.
You will want to modify the .snippet file associated with the pattern. For the one you are looking for it is, by default:
VisualStudioInstallDirectory\VB\Snippets\1033\common code patterns\conditionals and loops\ForEachNext.snippet
You can also track down the exact location by looking in
Tools > Code Snippets Manager..., select Visual Basic for the language and browse to Code Patterns - If, For Each, Try Catch, Property, etc - the file location will be listed there.

Excel VBA - How to stop auto formatting of scientific numbers to floating in VBA editor

I need to enter a series of equations into a VBA function. The equations contain coefficients in scientific notation and I need to keep this notation to allow easy checking of the VBA script.
However, as soon as I enter a scientific number in the VBA editor and hit Return, the number is automatically converted to a floating number. Although accuracy is not effected, readability suffers tremendously and makes checking very hard.
How can I suppress auto formatting in the VBA 7.0 editor?
For example, if I enter the following line in the VBA editor:
e = 3.472e-4 * d + 2.156e-7
and hit Return I end up seeing the following line
e = 0.0003472 * d + 0.0000002156
I need to somehow stop this auto-formatting nightmare.
You could make a 1-character wrapper for val like:
Function v(s As String) As Double
v = Val(s)
End Function
and then use expressions like:
e = v("3.472e-4") * d + v("2.156e-7")
that might minimize the impact on readability
alternatively -- why not just accept what the editor does but have comments that explain the background formula?
Another approach -- use another editor like Textpad for which VBA syntax highlighting is available (in Textpad's case you need to download a VBA syntax definition file from their website to enable highlighting). You'll lose intellisence but it still has some nice features. I haven't used Textpad for VBA since the built-in editor in Excel is adequate for me, but I have used Textpad extensively for some other languages and find it easy to work with. You could edit code in Textpad (or maybe Notepad++) and copy it over to the VBA editor when you want to test.

Decimal parsing differences on separate environments

Evening,
I'm bashing my head against a wall with the following problem:
I'm loading numbers from cells from a Number column with size=16
and decimal places = 2 inside adBase III .dbf file.
These numbers, when viewed with a DbfViewer appear as: 12345.12, where there is no thousands separator and the decimal
separator is ..
I parse the number from the cell in the database using decimal.parse(val).
I do stuff with that number.
I am using the ClosedXML library to paste the number into an .xlsx Excel file cell with the following formula: "=R[-1]C * 100/" & val where val is the value I obtained from the dBaseIII database file. This is done with the following statements:
Dim formula as String = "=R[-1]C * 100/" & project.TotalIncome(i)
cell.FormulaR1C1 = formula.
I am using two programming environments:
A Windows 8.1 machine with Visual Studio 2013 Community and Office 2010.
A Windows 8.1 machine with Visual Studio 2013 Ultimate and Office 2013.
I have made sure that both environments have the same Language, Date, Time and Number format, both for Windows and Office.
When I build and execute the program from the Option 1 Environment, everything pastes fine inside the Excel file. I navigate to the cell containing the formula, and whether or not the value obtained had decimal places, the formula is there.
However, If I build and execute the program from the Option 2 Environment, I get a:
Removed Records: Formula from /xl/worksheets/sheet.xml part
Removed Records: Formula from /xl/calcChain.xml part (calculation properties)
I tried adding a breakpoint in Environment 2, opening the Locals window and editing those values which had decimal places and everything worked as intended, whereas when I use Environment 1 I have no trouble whatsoever when the value has decimal places.
I have tried the following (in Environment 2):
Dim nfi As NumberFormatInfo = New CultureInfo("es-ES", False).NumberFormat
nfi.NumberDecimalSeparator = ","
value = Decimal.Parse(row("VALUECOL"), nfi)
also:
value = Decimal.Parse(row("VALUECOL"), New CultureInfo("es-ES"))
To no avail.
I have opened the XML file containing the Excel Sheet info in Environment 2 and found this:
<x:c r="L101" s="41">
<x:f>L100 * 100/57125,71</x:f>
</x:c>
Whereas the definitions for the same XML file created by the Environment 1 has the following cell value:
<x:c r="L101" s="41">
<x:f>L100 * 100/57125.71</x:f>
</x:c>
So, is it a Visual Studio Locale thing (which both have the same, as far as I can see), or am I missing something else?
EDIT: Printing out the current Locale with:
Console.WriteLine(CultureInfo.CurrentCulture.Name)
yields the same es-ES on both Environment 1 and Environment 2.
EDIT 2:
Taken from: Microsoft Office XML formats. Defective by design.
To save them time, Microsoft chose to store XML using the US English
locale regardless of all settings above. [...]
Also, for Excel formulas, it means the formula names are US English
formula names, [...] it implies you are willing to work with US English
function names (plus US English separators, ...).
So basically it all boils down (I believe) to a pre localisation of the decimal value into the Excel XML taking into account something, somewhere.
In Environment 2, any other (non-formula) value I write to the Excel file appears in the XML as an en-US localised value (i.e. 12345.12). Most of them brought in by a dataTable import. However, since writing a formula requires the input of a string, and Visual Studio applies locale settings to said string, it ends up as 12345,12 in the Excel XML, which results in the previously mentioned errors.
So, what on earth is Visual Studio taking from Environment 1 that is different from Environment 2? All possible UI localisation options are exactly the same in both machines...
I had a similar issue before, and found that there was a different dll file in my project references. The dll's were named the same, I only noticed because of a file size difference. Once I manually linked to the same one on both Dev machines, I got the expected results.
Like I said, my issue was different... But it did also involve excel files, and I did have Excel 2010 on one Dev machine and 2013 on the other.
I don't even know if this qualifies as an answer since I still have no clue about where's the localisation variable that Environment 1 has different from Environment 2.
However, It seems Visual Studio -when using different localisations- deals internally with de-localised decimal variables, but with localised string variables. Even when checking the locals panel during debugging, the value of a decimal number stored in a dictionary entry will appear as its localised version on the keyValuePair entry, and as a de-localised en-US value when expanded:
Hence, when outputting a dataTable as a whole to the Excel file, it's written onto the XML as en-US values. On the other hand, when outputting a formula (a.k.a. a string) it pours over the localised version of the associated decimal value.
Conclusion: When dealing with Office files in localised systems, just write the data as de-localised (i.e. en-US) and let the software localise it for you.
Ended up doing the following dirty patch:
Dim formula As String = "=R[-1]C * 100/" & project.TotalIncome(i).ToString().Replace(",", ".")

VB.Net Events Practice Help

I was given an assignment to "write a program to print only even numbers between 6 and 16 using events", but I don't even know where to begin. The main thing I am having difficulty with understanding in this assignment is how I am supposed to specify that it only print even numbers in the given range of numbers.
Am I going to have to do a Mod2 code for each individual number and have it exclude any with the result of 1? Or is there another piece of code specifically designed for such an occassion? Perhaps there is some type of equation I can have the program read in terms of a variable, which holds the values of 6, 8, 10, 12, 14, and 16? I am just genuinely confused on how this is supposed to be programmed. Any assistance would be greatly appreciated.
No offense, but I'm not at all convinced that you are accurately relaying you assignment, but...
Firstly, using MOD is a good starting point, particularly as you are supposedly tying this in with events...
To use events as part of your solution, I would suggest creating a textbox withevents and a handler for textchanged, then in a loop set the txtbox.Text property to the string representation of the loop index (say going from 1 to 20), then inside the textchanded event turn the propery back into an integer, check to see if it's within the proper range and even(using, as you suggested, MOD).
The following will help you solving a part of the problem:
Dim number as Integer = 6
While number <= 16
// PRINT Goes here ..
number = number + 2
End While
These Microsoft links are good learning resources:
Learning Visual Basic from the Ground Up
Getting Started with Visual Basic
Video How to: Creating Your First Visual Basic Program
Events in Visual Basic
Closer Look: Understanding Properties, Methods, and Events
Events and Event Handlers