r/visualbasic • • Oct 14 '20

Stumped with formula in code.

6 Upvotes

Apologies in advance if a) I come off as a total noob (I'm new to Visual Basic) and b) if this post is rather long. TL;DR: I need to calculate BMI using the values entered into the textbox objects I'm using and spit out the answer onto one of the labels.

So I find myself stumped on setting up a set of calculations to determine Body Mass Index (BMI) using either English units (pounds and inches) or Metric units (metres and kilograms). Here is the code I have for this part, so far:

'Here's where I attempt the BMI calculations. Wish me luck.
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
lblBMIHeader.Visible = True
lblBMI.Visible = True
'Here are the declarations. I'm seriously hoping I got this part right.
Dim decUS As Decimal
Dim decMetric As Decimal
Dim decHeight As Decimal
Dim decWeight As Decimal
If radUS.Checked = True Then 'The process that uses pounds and inches
decHeight = Convert.ToDecimal(txtHeight.Text)
decWeight = Convert.ToDecimal(txtWeight.Text)
If decHeight > 0 And decWeight > 0 Then
decUS = (decWeight / decHeight ^ 2) * 703
lblBMI.Text = decUS.ToString("00.0")
ElseIf (decHeight <= 0 And decWeight <= 0) Or (decHeight <= 0 Or decWeight <= 0) Then
MsgBox("Please try again. Only numbers greater than 0 should be in this field.", 16, "Entry Invalid")
txtHeight.Text = ""
txtWeight.Text = ""
txtHeight.Focus()
txtWeight.Focus()
Else
MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
txtHeight.Text = ""
txtWeight.Text = ""
txtHeight.Focus()
txtWeight.Focus()
End If
ElseIf radMetric.Checked = True Then 'The process that uses kilograms and metres
decHeight = Convert.ToDecimal(txtHeight.Text)
decWeight = Convert.ToDecimal(txtWeight.Text)
If decHeight > 0 And decWeight > 0 Then
decMetric = decWeight / decHeight ^ 2
lblBMI.Text = decMetric.ToString("00.0")
ElseIf (decHeight <= 0 And decWeight <= 0) Or (decHeight <= 0 Or decWeight <= 0) Then
MsgBox("Please enter a number greater than 0", 16, "Entry Invalid")
txtHeight.Text = ""
txtWeight.Text = ""
txtHeight.Focus()
txtWeight.Focus()
Else
MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
txtHeight.Text = ""
txtWeight.Text = ""
txtHeight.Focus()
txtWeight.Focus()
End If
End If
End Sub

And here is what the interface looks like in the designer (the above code is tied to the 'Calculate' button):

I have more to do with this program before it's completed but I'm stumped with how to calculate the values entered into the textbox objects. I thought that linking the values with 'And' statements would be the best way to solve the problem but it didn't work. I'm not sure how to proceed from here and was wondering if anyone here had any ideas?

Update: I added an IsNumeric statement and defined the values globally and set them equal to 0. I managed to stop it from accepting numbers less than or equal to 0. I tried entering non-numeric characters only for it to throw out an exception. This happened when either the "Imperial (US)" or the "Metric" radio buttons were selected. Here is the updated code beginning with the declarations:

Dim decHeight As Decimal = 0
Dim decWeight As Decimal = 0
Dim decUS As Decimal = 0
Dim decMetric As Decimal = 0

I decided to keep the decUS and decMetric decimal values in the code for now. These are closer to the beginning of the code. The updated version of the relevant code looks like this:

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
        lblBMIHeader.Visible = True
        lblBMI.Visible = True
        If radUS.Checked = True Then 'The process that uses pounds and inches
            decHeight = Convert.ToDecimal(txtHeight.Text)
            decWeight = Convert.ToDecimal(txtWeight.Text)
            'The "IsNumeric" statements should keep any non-numeric characters from becoming a problem.
            'The rule for both Metric and Imperial measurements is that we want numbers greater than 0.
            'Anything else should spit out an error message.
            If IsNumeric(txtHeight.Text And txtWeight.Text) Then
                If decHeight > 0 And decWeight > 0 Then
                    decUS = (decWeight / decHeight ^ 2) * 703
                    lblBMI.Text = decUS.ToString("00.0")
                Else
                    MsgBox("Please try again. Only numbers greater than 0 should be in this field.", 16, "Entry Invalid")
                    txtHeight.Text = ""
                    txtWeight.Text = ""
                    txtHeight.Focus()
                    txtWeight.Focus()
                End If
            Else
                MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
                txtHeight.Text = ""
                txtWeight.Text = ""
                txtHeight.Focus()
                txtWeight.Focus()
            End If
        ElseIf radMetric.Checked = True Then 'The process that uses kilograms and metres
            decHeight = Convert.ToDecimal(txtHeight.Text)
            decWeight = Convert.ToDecimal(txtWeight.Text)
            If IsNumeric(txtHeight.Text And txtWeight.Text) Then
                If decHeight > 0 And decWeight > 0 Then
                    decMetric = decWeight / decHeight ^ 2
                    lblBMI.Text = decMetric.ToString("00.0")
                ElseIf (decHeight <= 0 And decWeight <= 0) Or (decHeight <= 0 Or decWeight <= 0) Then
                    MsgBox("Please enter a number greater than 0", 16, "Entry Invalid")
                    txtHeight.Text = ""
                    txtWeight.Text = ""
                    txtHeight.Focus()
                    txtWeight.Focus()
                End If
            Else
                MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
                txtHeight.Text = ""
                txtWeight.Text = ""
                txtHeight.Focus()
                txtWeight.Focus()
            End If
        End If
    End Sub

I'm a bit closer but I suspect I'm going to need to focus my attention elsewhere. This assignment requires that I add more things to the program (including a loop and a pictureBox object with 2 pictures in it). Wish me luck.

Update 2: I solved the problem I was running into where entering a non-numeric character, or nothing at all for that matter, would spit out an exception. The problem I ran into is that I had 1 IsNumeric handling input from both textboxes. I also moved the Convert statements below the Isnumeric statements. The new code looks like this:

'Here's where I attempt the BMI calculations. Wish me luck.
    Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
        lblBMIHeader.Visible = True
        lblBMI.Visible = True
        If radUS.Checked = True Then 'The process that uses pounds and inches
            'The "IsNumeric" statements should keep any non-numeric characters from becoming a problem.
            'The rule for both Metric and Imperial measurements is that we want numbers greater than 0.
            'Anything else should spit out an error message.
            If IsNumeric(txtHeight.Text) And IsNumeric(txtWeight.Text) Then
                decHeight = Convert.ToDecimal(txtHeight.Text)
                decWeight = Convert.ToDecimal(txtWeight.Text)
                If decHeight > 0 And decWeight > 0 Then
                Else
                    MsgBox("Please try again. Only numbers greater than 0 should be in this field.", 16, "Entry Invalid")
                    txtHeight.Text = ""
                    txtWeight.Text = ""
                    txtHeight.Focus()
                    txtWeight.Focus()
                End If
                decUS = (decWeight / decHeight ^ 2) * 703
                lblBMI.Text = decUS.ToString("00.0")
            Else
                MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
                txtHeight.Text = ""
                txtWeight.Text = ""
                txtHeight.Focus()
                txtWeight.Focus()
            End If

        ElseIf radMetric.Checked = True Then 'The process that uses kilograms and metres

            If IsNumeric(txtHeight.Text) And IsNumeric(txtWeight.Text) Then
                decHeight = Convert.ToDecimal(txtHeight.Text)
                decWeight = Convert.ToDecimal(txtWeight.Text)
                If decHeight > 0 And decWeight > 0 Then
                ElseIf (decHeight <= 0 And decWeight <= 0) Or (decHeight <= 0 Or decWeight <= 0) Then
                    MsgBox("Please enter a number greater than 0", 16, "Entry Invalid")
                    txtHeight.Text = ""
                    txtWeight.Text = ""
                    txtHeight.Focus()
                    txtWeight.Focus()
                End If
                decMetric = decWeight / decHeight ^ 2
                lblBMI.Text = decMetric.ToString("00.0")
            Else
                MsgBox("Please enter a positive number in the text boxes.", 16, "Entry Invalid")
                txtHeight.Text = ""
                txtWeight.Text = ""
                txtHeight.Focus()
                txtWeight.Focus()
            End If
        End If

    End Sub

Now I have to come up with a way to throw some pieces of garbage code into my program before noon tomorrow (and by "garbage code" I mean code that has garbage pieces in it that don't do anything). Wish me luck.


r/visualbasic • • Oct 05 '20

Live data in program

6 Upvotes

I’m making a stock exchange simulator, how can I get live updated share prices into my program?I tried reading from an excel file, but the data has to be manually refreshed.


r/visualbasic • • Sep 19 '20

Article The Most Popular Programming Languages - 1965/2020

Thumbnail
youtu.be
6 Upvotes

r/visualbasic • • Aug 03 '20

VB.NET Help Thank you to all who've helped me. You've helped me to make a user community happy.

6 Upvotes

https://github.com/EightBitz/Dungeondraft-Tools

https://github.com/EightBitz/Dungeondraft-Custom-Tags

I know there's room for improvement in my code, but everything seems to work. Thank you for your help.


r/visualbasic • • Jul 20 '20

VB.NET Help Help with replace.

6 Upvotes

Hi, all. I'm using Visual Basic 2019 Community. I'm writing an app where I need to load a text file that contains a list of image files. Within the content of that text file, I want to replace all relevant file extensions with .webp.

So if the file names are listed as such:

Image1.bmp

Image2.Png

Image3.JPEG

I want toe result to be:

Image1.webp

Image2.webp

Image3.webp

For this particular question, I'm not asking about changing the actual filenames on disk. I'm asking about changing the content of a text file that contains the list of filenames.

My issue is that the .Replace method is case-sensitive, and I don't know how to work around that. I need to change any iteration of the file extensions, regardless of case.

I don't know how to use regex, and when I look at examples, my head hurts. My current code is below. I would appreciate any help.

Thank you in advance.

Dim FileTypes() As String = {".bmp", ".dds", ".exr", ".hdr", ".jpg", ".jpeg", ".png", ".tga", ".svg", ".svgz", ".webp"}

FileContent = My.Computer.FileSystem.ReadAllText(file)
For Each Extension In FileTypes
    FileContent = FileContent.Replace(Extension, ".webp")
Next

r/visualbasic • • May 15 '20

Input Box help

6 Upvotes

I have an assignment that I am working on where I am supposed to input a grade in an input box and repeat with a repetition structure 5 times and then display an average grade and letter grade. I think they key part I am struggling with is how to sum my 5 grades in one variable. The math is only being performed on the last enrty.

I was put in this class as an alternative to a LabVIEW class that was canceled so I'm really new to this and the instructor told me to find the information I need online. Can anyone help a newbie out a bit? Thanks!

Code<

Public Class frmStudentGrades

'declare variables

Dim intNum As Integer = 0

Dim intCounter As Integer = 0

Dim strgrades As String = 0

Dim blngrades As Boolean

Dim intGrades As Integer = 0

Dim intAverage As Integer = 0

Dim strLetterGrade As String = Nothing

Dim blnIsNumeric As Boolean

Private Sub btnEnterGrades_Click(sender As Object, e As EventArgs) Handles btnEnterGrades.Click

'increment counter

For intCounter = 1 To 5

strgrades = InputBox("Please Enter Grade", "0 to 100")

blnIsNumeric = Integer.TryParse(strgrades, intGrades)

Next intCounter

'if numeric and 0-100 assign grade

If blnIsNumeric Then

If intGrades >= 0 And intNum <= 100 Then

' intNum = intGrades

Select Case intAverage

Case intAverage >= 93

strLetterGrade = "A"

Case intAverage >= 86 To intAverage <= 92.99

strLetterGrade = "B"

Case intAverage >= 77 To intAverage <= 85.9

strLetterGrade = "C"

Case intAverage >= 70 To intAverage <= 76.9

strLetterGrade = "D"

Case intAverage < 70

strLetterGrade = "F"

End Select

intAverage = intGrades / 5

lblLetterGrade.Text = strLetterGrade

lblTestAverage.Text = intAverage

Else

MessageBox.Show("Please enter value of 0-100")

End If

Else

MessageBox.Show("Please enter only numbers")

End If

End Sub

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click

'Exit

Me.Close()

End Sub

Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click

lblLetterGrade.ResetText()

lblTestAverage.ResetText()

intGrades = Nothing

intAverage = Nothing

End Sub

End Class


r/visualbasic • • Apr 15 '20

Visual Basic and DataTables Guide

6 Upvotes

Hello!

I have struggled with data tables, how to use them, and understand all the methods for them. If I can't find code close enough to what I want to do, then I can't use them. I was wondering if there was a video tutorial series that does an in-depth explanation of data tables and how to use them to different things properly..? I want to learn to think for myself when utilizing them and not just find other people's code.


r/visualbasic • • Mar 27 '20

Visual Basic Dungeons and Dragons Dice Roller Help

6 Upvotes

So for my Visual Basic Programming class, we have to make our own project. I am trying to make a dungeons and dragons dice roller, but I am having trouble getting the Rnd function to roll dice depending on the amount of dice the user wants to roll.

For Example: If the user wants to roll five 6 sided die, the program should roll the D6 five times and add them all together. Then display the added number.

If you would like to message me and ask me further questions, feel free! Thanks for the help in advance!

/preview/pre/zsazyk6nk9p41.png?width=445&format=png&auto=webp&s=2ea75889e265ee419af6b413aa79a702dfe3b6f8

/preview/pre/eutrigflk9p41.png?width=1805&format=png&auto=webp&s=4b43de26da203378399544a66674a96fbe67911e


r/visualbasic • • Mar 04 '20

VB.NET Help Declare and Instantiate List(Of KeyValuePair(Of String, String))

6 Upvotes

I am trying to code my own Enigma machine for no reason other than I watched a video on how they work and now I'm intrigued.

I'm trying to make an emulation of the wiring of the rotors and the best thing to do looks like the List(Of KeyValuePair(Of String, String)). I know how to add to it, but I just want to fill it during the declaration instead, as the values won't ever change

Now I know how to do it with a simple list, for example

Public wiring as New List(Of String) ({"A", "B"})

But if I do it like that for KeyValuePair it throws an error

Public wiring as New List(Of KeyValuePair(Of String, String)) ({"A","B"} {"C","D"})

I get an "Overload resolution failed because no accessible 'New' accepts this number of arguments"

How do I do it?


r/visualbasic • • Feb 22 '20

VB.NET Help Why I don’t see the Machine Learning tool? I can’t add it? (Vb.net)(ML.NET Model Builder)

Post image
6 Upvotes

r/visualbasic • • Feb 20 '20

Pass argument from vb to a cmd app

6 Upvotes

We have a list we need to input into a cmd app. What's the easiest way to pass values in rows into command prompt?


r/visualbasic • • Feb 11 '20

Question from a Newbie

6 Upvotes

So at my new job I'm being asked to use things I never studied in school, such as some light programming stuff. So here's my question!

So say I have hundreds of word documents spread about in different files. These word documents all contain the same type of information just applied to different "objects" if you will. For example for object A there is a bunch data along with a word document in the in object A's file. Same goes for object B, C, D and so on. Is there any type of code I could write in VBA that could compile just the word documents in one file? Obviously i could just do this manually but their are hundreds of files.

Thanks!


r/visualbasic • • Jan 12 '20

Need a bit help

6 Upvotes

So ive done a program and my teacher just casually said its spagheti code and i need to somehow fix it but im totally out of idea how to do that so i would appreciate all help i can get from here!
Here is the code:
https://pastebin.com/qzPbMXh8


r/visualbasic • • Jan 07 '20

How to make a button invisible?

6 Upvotes

r/visualbasic • • Dec 03 '19

Help with running an old visual basic game on Windows 10

6 Upvotes

I have the file for an old game from my uncle he got years back. It was written in Visual Basic in 1995, and when I run the application, I get an error stating "This app can't run on your PC". I believe I may need to run the program in visual studio, but I'm far from an expert and can only get the text files to open and haven't had any luck running the .exe itself. I think I might need to write a code to call the .exe file based on some brief online research, but I can't get it to work. Any advice would be much appreciated!


r/visualbasic • • Aug 15 '19

Limiting number of characters in string, Noob question

6 Upvotes

Hello All,

I've written a quick program to convert a C Temp Value to F Type Value. It works perfect. However, I just want it show the first two numbers. For instance, I want it to show 74 rather than 74.533.

Here is what I wrote:

Dim tempF As String

tempF = ((tempC * (9 / 5)) + 32)

label4.text = TempF

How do I truncate the value?

Thank you very much!

EDIT: Quick typo fix


r/visualbasic • • Jul 26 '19

VB6 Help Where to learn Visual Basic?

6 Upvotes

It's been a long time since I have done any programming. Like 30 years and obviously things have changed a lot since Sinclair/BBC/Commodore BASIC; and the COBOL and FORTRAN I studied whilst studying accountancy (with a but of DOS thrown in too) - where one of the subjects was Systems Analyst which (seriously) included punch card design - and that was antiquated in the 80s.

So, I have decided (perhaps insanely) to learn visual basic - but where are the best resources to be found to teach myself?


r/visualbasic • • Jun 30 '19

Visual Basic VS2010: Best Method Of Software Protection

6 Upvotes

I am new here. Just joined moments ago. I was wondering if any of you would care to share your input on the methods you use to protect your software for activation and also if you check for anything on start up or in intervals after activation? What's the most secure method of software activation and most secure way to check that any sort of key or GUID hasn't been compromised and floated around to others who are trying to pirate the software. Any examples you can show me or articles. I'm interested in learning more about software protection and security.

Thanks.


r/visualbasic • • Jun 05 '19

Save a webpage that uses Ajax

6 Upvotes

I run a number of programs that I've written to download and parse webpages, but pages that use Ajax are a problem. I find that using Chrome and saving the complete webpage will save an HTML file with the needed data, but communicating with Chrome is a problem. Has anyone been successful in integrating Chrome or other browser to be able to programmatically save an Ajax page?


r/visualbasic • • May 08 '19

VB6 Help Visual basic 6

6 Upvotes

So applying for a job that entails using vb6. Not guarantees I'll get it. But the more i can learn the happier i am. It looks like you can download vb6 for free so i was wondering what kind if project would be ideal for getting a general feel for the language? My current understanding is its kind kf between C and C#


r/visualbasic • • May 07 '19

VB.NET Help I have visual studio 2019 , but i cannot find my .exe

6 Upvotes

I wrote a math formula in visual studio in a .net form app . It runs but i cannot find the .exe file in visual basic folders ( the folders are actually empty for me )


r/visualbasic • • Apr 04 '19

Variables issue

6 Upvotes

Hi ppl, i'm not that pro person in VB.

what i'm trying to do is to assign a variable for an item (e.g. Label or Textbox)

a variable looks like their name and the other properties so when i'm in any sub in the code, i can call that variable like: Label1.VarName

i know this is a wrong way but is there any way to such a thing ?

Thanks.

My code:

Dim n As Integer

Private Sub TextBox1(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown

If e.KeyCode = Keys.Enter Then Create_new_list_item()

End Sub

Sub Create_new_list_item()

ReDim _labels(n)

_labels(n) = New Label()

With _labels(n)

Dim MyN As Integer = n

.Name = "Label_" + n.ToString

.Text = MyN.ToString

.Width = 100

.Visible = True

.Location = New Point(0, 70 + (n * 24))

AddHandler .DoubleClick, AddressOf Editvalue

End With

Me.Panel1.Controls.Add(_labels(n))

n += 1

End Sub

Sub Editvalue(ByVal sender As Object, ByVal e As EventArgs)

sender.Visible = False

MsgBox(sender.MyN.ToString)

End Sub


r/visualbasic • • Mar 18 '19

Space Invaders issue

6 Upvotes

I am creating a space invaders game and I am having trouble with the invaders going faster. When they die and come back, they start going faster,but after a while they stop abruptly. They don't move. Can someone help me figure out what to do?

Private Sub skullmovement()

        If PictureBox1.Left >= 5 And border = True Then

            For i As Integer = 1 To 20

                pic(i).Left += fast

            Next

            If PictureBox1.Left > (Me.Width - 550) Then

                border = False

                For i As Integer = 1 To 20

                    pic(i).Top += 20

                Next

            End If

        ElseIf PictureBox1.Left < (Me.Width - 500) And border = False Then

            For i As Integer = 1 To 20

                pic(i).Left -= fast

            Next

            If PictureBox1.Left < 10 Then

                border = True

                For i As Integer = 1 To 20

                    pic(i).Top += 20

                Next

            End If

        End If

        For i As Integer = 1 To 20

            If pic(i).Bounds.IntersectsWith(picbshooter.Bounds) And picbshooter.Visible = True And pic(i).Visible = True Then

                skulltimer.Stop()

                lbldead.Visible = True

                lives -= 1

            End If

        Next

        If num = 20 Then

            For i As Integer = 1 To 20

                pic(i).Visible = True

                skulltimer.Stop()

                skulltimer.Start()

                item = 1

                num = 0

            Next

            fast += 5

        End If

    End Sub


r/visualbasic • • Feb 23 '19

Interacting with programmatically created items

6 Upvotes

I am fooling around with creating thing dynamically in code(buttons, text boxes, simple thing). So far I understand the very basics of creating them. For example for a combobox I do:

Dim combobox As New ComboBox
            With combobox
                .Location = New Size(20 * i, 20 * i)
                .Name = "Combobox1"
                .Items.Add("one")
            End With
            Me.Controls.Add(combobox)

I put this on a button and it makes the combobox appears. My question is, after its been generated, how can I interact with it?

I have the .name property to label it as Combobox1, but when I try to add something outside of the With|EndWith box that refers to combobox1 I get an error that says it is undefined or unavailable due to protection level.

How can I interact with it once its been created, or is that not something thats done?


r/visualbasic • • Jan 09 '19

how can i get the color of a pixel using screen coordinates? (already got the code, but it only reads cursor coordinates not static ones, need fixed screen locations)

6 Upvotes

hey everyone!

i want to check one pixel on my screen and read its color code

ive already sound a code wich works fine but it ony reads the pixel using my mouse/Cursor locations, how can i modify the code to use fixed coordinates?

        Using bmp As New Bitmap(1, 1)
            Using g As Graphics = Graphics.FromImage(bmp)
                g.CopyFromScreen(Windows.Forms.Cursor.Position, New Point(0, 0), New Size(1, 1))
            End Using
            Label1.Text = bmp.GetPixel(0, 0).ToString

thanks in advance!