How to subtract from a number with a variable amount of other numbers? - vb.net

Sorry for the edits, im tired and im a moron, so heres my problem=
Lets say this is my code :
Dim ogquantity,subtractedquantity as double
Private Sub CalculateMe
ogquantity = numericupdown1.value
subtractedquantity = ogquantity - numericupdown2.value
subtractedquantity = ogquantity - numericupdown3.value
subtractedquantity = ogquantity - numericupdown4.value
subtractedquantity = ogquantity - numericupdown5.value
label1.text = subtractedquantity
End Sub
And i set "CalculateMe" as code for 1-5 numericupdowns_valuechanged
This wont output a changed value..
And the reason i have it set up like this is because in the actual code numericupdown might change subtractedquantity1 or subtractedquantity28, it is decided with a dropdown menu for each numericupdown.
something like this:
Dim item1stock, item1originalstock As Double
If itemselector1name.Text = itemdefiner1name.text Then
item1stock = item1originalstock - itemselector1quantity.value
itemselector1label.text = item1stock
End If
If itemselector2name.Text = itemdefiner1name.text Then
item1stock = item1originalstock - itemselector2quantity.value
itemselector2label.text = item1stock
End If
and i would repeat check for every item like this but if two different 'itemselectorquantity' is supposed to subtract from the same original stock quantity that i dont know how to set up.. Im trying my best here but im new to coding and bad at explanation. Thank you!

Your question is rather muddled but, as an example of the sort of thing you might do if you want to use zero, one or more of a set of controls based on another set of controls, consider this example that uses CheckBoxes to specify which NumericUpDowns to subtract from an initial quantity:
Private Function SubtractCheckedValues(value As Decimal) As Decimal
Dim checkBoxes = {CheckBox1, CheckBox2, CheckBox3, CheckBox4}
Dim numericUpDowns = {NumericUpDown1, NumericUpDown2, NumericUpDown3, NumericUpDown4}
For i = 0 To checkBoxes.GetUpperBound(0)
If checkBoxes(i).Checked Then
value -= numericUpDowns(i).Value
End If
Next
Return value
End Function

Related

Visual Basic: Simple Counter with leading Zero

I am trying to create a simple counter that increases when the button is clicked.
What I would like is when the counter is clicked it displays "01", "02" etc.
I can create it already with "1", "2", but I would like to have a leading zero.
I have searched and found I can do this by converting the label to a string, but I cant seem to get the value to count?
If I change "count.text = counter" to "count.text = cot" it will display "01", but wont count. I'm guessing this is due to the fact its only displaying what is currently in the string but not increasing the value?
If I could get any guidance that would be great!
Many thanks!
Dim counter As Integer = 1
Dim cot As String = String.Format("{0:00}", counter)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
counter = cot + 1
count.Text = counter
End Sub
PadLeft is the key.
Dim number as Integer = 12
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 12
number = 2
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 02
The problem is, that you don't update your formatted number properly. It's only initialized a single time.
To increment the counter, use counter += 1 or counter = counter + 1 first. This will add 1 to the current value of the integer variable. Then modify the text of your Label by calling that formatting code again: count.Text = String.Format("{0:00}", counter).
This should get you started...
it converts the string into an integer. increments the number, converts it back into a string and then checks for a leading 0, if not found it adds it.
I will let you convert it into your button click for practise, as it should help you have a good understanding of the conversion between types :)
Sub string_counter()
Dim string_counter As String
string_counter = "00"
For x = 0 To 10
Debug.Print string_counter
string_counter = Int(string_counter) + 1
string_counter = Str(string_counter)
If Left(Trim(string_counter), 1) <> "0" Then
string_counter = "0" + Trim(string_counter)
End If
Next x
End Sub

For loop not working right unless i add Msgbox inside of loop

Hello there everyone.
I have little problem, didn't make sense at all. So i have kinda simple for loop. I want to create random integers and remove index of specific array by that integer.
Working perfect:
For i = 1 To CInt(rastgelesoru.Text)
Dim Rand As New Random()
Dim xIndex As Integer = Rand.Next(0, AList.Count - 1)
Dim SelectedValue = AList(xIndex)
Dim eklepanelrnd As Panel = CType(containerpanel.Controls(SelectedValue), Panel)
If eklepanelrnd.Tag = "1" Then
MsgBox(xIndex)
containerpanelrastgele.Controls.Add(eklepanelrnd)
End If
AList.RemoveAt(xIndex)
Next
For example i have 500 element in array. When i add message box like above, it works perfect. I get random numbers. (100,65,355,27,472 last output for 5). But when i remove msgbox line i get Consecutive numbers everytime. First i thought it might be really 'random' but no. Everytime i get Consecutives. (23,24,25,160,161 last output for 5 without msgbox line.)
Not working properly without msgbox line.
For i = 1 To CInt(rastgelesoru.Text)
Dim Rand As New Random()
Dim xIndex As Integer = Rand.Next(0, AList.Count - 1)
Dim SelectedValue = AList(xIndex)
Dim eklepanelrnd As Panel = CType(containerpanel.Controls(SelectedValue), Panel)
If eklepanelrnd.Tag = "1" Then
containerpanelrastgele.Controls.Add(eklepanelrnd)
End If
AList.RemoveAt(xIndex)
Next
#AlexB. on comments.
DonĀ“t create Random objects in your loop but only create one. So move Dim Rand As New Random() before the loop.
Working perfect now. Thanks <3 Have a wonderful day.

Base data sheet form will not display calculated Field

I have a Data Sheet form which has a calculated field column. However the field will not display even though it has the correct value. The field in question is "numRisk":
Sub Calculate_Risk (Form As Object)
Dim OrderPrice, IfDonePrice, TotBrSymComm, BrComm, Risk As Double
Dim Symbol As String
Dim IntRateMult, noContracts As Integer
If MinTick = 0 OR Rate = 0 Then
Exit Sub
End If
Symbol = RTrim(Form.getByName("txtSymbol").CurrentValue)
If Symbol = "" Then
Exit Sub
End If
OrderPrice = Form.getByName("fmtOrder_Price").CurrentValue
IfDonePrice = Form.getByName("fmtIf_Done_Price").CurrentValue
noContracts = Form.getByName("fmtNo_Contracts").CurrentValue
If NOT USIntRates Then
Risk = ABS(OrderPrice - IfDonePrice) / MinTick
Else
Risk = ABS(OrderPrice\1 - IfDonePrice\1) * MinTick
IntRateMult = IIf(Symbol = "FV" OR Symbol = "TU",400, 200)
Risk = ABS(Risk - IntRateMult * ABS(OrderPrice - OrderPrice\1
IfDonePrice + IfDonePrice\1))
End If
Risk = Risk * MinTickVal / Rate
TotBrSymComm = BrSymComm + BrSymCommAud
BrComm = IIf(TotBrSymComm = 0, BrCommission, BrSymCommAud + BrSymComm/Rate)
Risk = noContracts*(Risk + BrComm * 2)
Form.getByName("numRisk").Value = Risk
End Sub
The subroutine is called from the following routine which is triggered when the form is loaded:
Sub FromListForm(Event as Object)
Dim Form As Object
Dim TodaysDate As New com.sun.star.util.Date
Dim CurrDate As Date
Form=Event.Source.getByName("MainForm_Grid")
Form.RowSet.first()
Do Until Form.RowSet.isAfterLast()
Get_Contract(Form)
Get_Broker_Comm(Form)
Calculate_Risk(Form)
If isEmpty(Form.getByName("OrderDate").Date) Then
CurrDate = Date()
TodaysDate.Day = Day(CurrDate)
TodaysDate.Month = Month(CurrDate)
TodaysDate.Year = Year(CurrDate)
Form.getByName("OrderDate").CurrentValue = TodaysDate
End If
Form.RowSet.next()
Loop
Form.RowSet.last()
End Sub
Also is there a more efficient method to cycle through the rows? As this seems so slow I can see the row pointer moving down the table as each row is processed.
If I understand correctly, you're trying to enter individual values into each cell in a column of a tablegrid control? I don't believe that's possible.
Inside a tablegrid control, all values have to come from the underlying query. I recommend writing a query to do these calculations, and using that query as the basis for the form - that would solve both the problem of displaying the calculated result as well as improving the load speed of the form (since database logic in determining query results is almost always more efficient than a macro going row-by-row).
Alternately, you could have the calculated field be standalone, showing only the calculated result for the currently selected row of the tablegrid control. In this scenario, the "form loaded" event would only do the calculation for the first row, and the calculating macro would be triggered each time the row selection changed.

Excel VBA: Searching for value in listbox based on value set in textbox

I am trying to write a code for a search button which searches a listbox based a specific input set in a textbox.
The values searched are always numbers, and the listbox contains values from a single column.
The code i wrote can be found below but i don't understand why it is not functional.
Legend:
SearchButton: A Button which upon clicking is supposed to initiate the search
SearchBox: The textbox which will contain the search value
AvailableNumberList: The listbox which contains the data
Thanks for your help :)
Private Sub SearchButton_Click()
Dim SearchCriteria, i, n As Double
SearchCriteria = Me.SearchBox.Value
n = AvailableNumberList.ListCount
For i = 0 To n - 1
If SearchCriteria = i Then
AvailableNumberList.ListIndex = i
End If
Next i
End Sub
Is this what you are trying?
'If SearchCriteria = i Then
If AvailableNumberList.List(i) = SearchCriteria Then
Also use Exit For once a match is found :)
Additional to #Siddharth Rout solution, this code allows to search in the ListBox even if the TextBox does not have the full word/number:
Private Sub SearchButton_Click()
Dim SearchCriteria, i, n As Double
SearchCriteria = Me.SearchBox.Value
n = AvailableNumberList.ListCount
For i = 0 To n - 1
If Left(AvailableNumberList.List(i),Len(SearchCriteria))=SearchCriteria Then
AvailableNumberList.ListIndex = i
Exit For
End If
Next i
End Sub
Thanks everyone for their code! =D

How to change my code to work a certain number of times?

My code gets a list of words from a txt file and chooses the words randomly. However, the same word can appear more than once and i need to know how to stop this from happening?
Here is the code:
Dim aryName As String() = Nothing
aryName = File.ReadAllLines(Application.StartupPath & "\Random\fnames.txt")
Dim randomWords As New List(Of String)
For i = 0 To aryName.Length - 1
If randomWords.Contains(aryName(i)) = False Then
randomWords.Add(aryName(i))
End If
Next
Dim random As New Random
Label2.Text = (randomWords(random.Next(0, randomWords.Count - 1)).ToString)
Maybe this might work, although it's in english and not code :(
if label1.text is changed then
Get label1.text
if label.text becomes this word again then
run the random code
end if
end if
This should prevent immediate repeats:
Dim random As New Random
'Just create a temporary holder for comparison
Dim word As String = Label2.Text
'Run a while loop that works as long as there
'is no change to the word. This should prevent
'back to back repeats.
While word = Label2.Text
word = (randomWords(random.Next(0, randomWords.Count - 1)).ToString)
End While
Label2.Text = word
If you don't want it to repeat ever again, you should probably remove the used word from the randomWords List.
Dim random As New Random
Label2.Text = (randomWords(random.Next(0, randomWords.Count - 1)).ToString)
randomWords.Remove(Label2.Text)
You can a) remove the selected word from the list, or b) you can random sort the list first.
Option a) is already addressed in another answer
Option b) lets you retain all the words in memory. Here is the code:
Dim randomWords As New List(Of String)(File.ReadAllLines(Application.StartupPath & "\Random\fnames.txt"))
Dim random As New Random
randomWords.Sort(Function(s1 As String, s2 As String) random.Next(-1, 1))
For index As Integer = 0 To randomWords.Count - 1
Label2.Text = randomWords(index)
Next
Modify your For loop to prevent dupes in aryName from getting into randomWords:
For i = 0 To aryName.Length - 1
If randomWords.Contains(aryName(i)) = False Then
randomWords.Add(aryName(i))
End If
Next