a newb practising more vb.net code.
I currently have four identical comboboxes named box1, box2, box3, box4.
in each of those comboboxes I have a list of words-
dog
cat
bird
fish
I've added these words through the 'properties'->'items'-->'collections' tab.
For now, I want to display a message- "you have 4 cats!" If the user selects the word 'cat' for all four comboboxes.
How would I write this code? I'm guessing I introduce a private function like 'onlycats' that sees if 'cat' is chosen for all 4 boxes... but I'm not to sure how to code based on what the user has chosen from the combobox.
So you want to count the selection of a ComboBox and present the results as a MsgBox after the User pressed a Button. You can do it like this:
Dim Selection(4) As String
Selection(0) = box1.Text
Selection(1) = box2.Text
Selection(2) = box3.Text
Selection(3) = box4.Text
MsgBox("You selected " & Selection.Where(Function(value) value = "dog").Count & " dogs!")
First of all I added everything to a Array and then search for a specific value and count it. You can count it like this:
Selection.Where(Function(value) value = "value").Count
The output is a Number. If "dog" is selected in all 4 boxes then the output is just 4 and you can write a Text around it. Hope it brings you on the right track.
============
If you just want to trigger something when 4 cats are selected then the count function also helps you. Just make a If Function
If Selection.Where(Function(value) value = "cat").Count = 4 Then
MsgBox("you have 4 cats!")
End If
Untested code but something like this:
sub CheckSame
if box2.SelectedValue = box1.SelectedValue
andalso box3.SelectedValue = box1.SelectedValue
andalso box4.SelectedValue = box1.selectedValue then
message.text = "You have 4 " & plural(box1.SelectedValue) & "!"
else
message.text = "You don't have 4 of the same animal"
end if
end sub
function plural(s as String) as String
select case s
case "fish"
return "fish"
case else
return s & "s"
end select
end function
Related
A background to why im trying to do this.
I am creating a program for work, this is one of many way of doing this process, where users select test that they have carried out, around 50 possible test using a userform that I've made. From the selection it runs through each userform based off which checkboxes were ticked, without the need to choose another test.
i.e. if they select 1,2,5 then the program will eventually load UserForm1 -> UserForm2 -> NOT UserForm3 -> NOT UserForm4 -> UseeForm5
The idea is that the user selects the options they want then based off the options selected create an array of either 0 if they didn't select the option or (1,2,3,4...) if they did, this number depends upon which checkbox was selected. i.e CheckBox1 = 1 CheckBox2 = 2 etc.
From this array I think i'll be able to select the correct userform using the .find feature in excel with a for loop.
But I have an issue when I run my code below,
Sub List_Create()
Dim tests(5) As Integer
If CheckBox1.Value = True Then
tests(0) = 1
Else: tests(0) = 0
End If
If CheckBox2.Value = True Then
tests(1) = 2
Else: tests(1) = 0
End If
If CheckBox3.Value = True Then
tests(2) = 3
Else: tests(2)= 0
End If
If CheckBox4.Value = True Then
tests(3) = 4
Else: tests(3) = 0
End If
If CheckBox5.Value = True Then
tests(4) = 5
Else: tests(4) = 0
End If
End Sub
I get a
runtime 424 error object required.
Which when debugged is on the line If CheckBox1.Value = True Then
Where have i gone wrong with my code? Is this possible, im not sure if it is?
You need to explicitly reference the userform to evaluate the checkbox value.
If userformX.CheckBox1.Value = True Then
My ultimate goal is to load a comboBox with elements from different arrays (vba coded). I have 8 different arrays and 6 option buttons. The first 2 optionButtons are grouped to eliminate 4 arrays which leaves the last 4 grouped optionButtons to determine the actual input for the combo box.
It works like this:
'first grouped option buttons
maleOptionButton
femaleOptionButton
'second grouped option buttons
basketballOptionButton
footballOptionButton
soccerOptionButton
hockeyOptionButton
The array's as you can guess are filled with student names that play the sports. So when the user clicks the first grouped buttons of Male/Female the click even does nothing.. however when they click the second group of option buttons of sports, it calls the same sub procedure within a module that has IF's and Else Ifs to determine the combination of buttons that were selected.
sub maleInitArray()
'declaration section:
Public maleSoccerArray(1 to 6) as string
'sub section
dim mike as student 'calls the class student
set mike = new student
with mike
.name = "Michael"
.age = 14
.so on and so on = something
end with
maleSoccerArray(1) = mike.name
End Sub
What I'm trying to do is this:
dim i as integer
dim l as integer
dim gender as string
dim sport as string
if inputForm.soccerOptionButton.value = true then
if inputForm.maleOptionButton.value = true then
gender = "male"
sport = "maleSoccerArray"
call male.maleInitArray ' inits the array thats hard coded.
else
gender = "female"
sport = "femaleSoccerArray"
call female.femaleInitArray
Else If...
' the list goes on to assign variables depending on the combo boxes.
' doesn't work, but it beats using this every time
l = UBound(sport) ' Doesn't recognize "sport" as an Array
for i = 1 to l
' .AddItem(gender.sport(i)) will not work as well.
inputForm.studentComboBox.AddItem(gender.sport(i))
next i
Seems as though UBound(variable) and AddItem(Variable.Variable)
will not work...
I found a few things so far, but none of them have worked.. such as the application.run method and assigning the actual "male.maleSoccerArray" method.
Any help would be greatly appreciated.. thanks
I have an Excel "Sheet1" with option buttons and 2 control buttons (OK, Clear)
The object of this Sheet is to learn some coding with controls.
D6:D14 (contents to be copied)
P6:P14 (if option button1 is true, then paste here)
Q6:Q14 (if option button2 is true, then paste here)
The same needs to be repeated or looped for the rest of the rows.
This is the code for row 6, option buttons are paired as optionbutton1&2, 3&4, 5&6, etc...
Private Sub CommandButton1_Click()
If Sheet1.OptionButton1.Value = True Then
Range("P6").Select
ActiveCell.FormulaR1C1 = "=RC[-12]"
Range("P6").Select
Range("Q6").Clear
Else
Range("Q6").Select
ActiveCell.FormulaR1C1 = "=RC[-13]"
Range("Q6").Select
Range("P6").Clear
End If
This approach isn't very flexible but makes the code a little easier.
Name each option button with an underscore and number like this: optionButton_1
Name each option button group the same way, but with the number being the row that the cell is on. For example, option buttons related to cell D6 could be group btnGroup_6
Now you can loop through each option button and use the button and group names to easily determine destination like this:
Private Sub btn_OK_Click()
Dim oOption As OLEObject
For Each oOption In Sheet1.OLEObjects
If oOption.OLEType = 2 Then
If oOption.Object = True Then
GroupNumber = Split(oOption.Object.GroupName, "_")(1)
ButtonNumber = Split(oOption.Name, "_")(1)
'Test is button is odd or even to determine destination
If ButtonNumber Mod 2 Then
Range("D" & GroupNumber).Copy Destination:=Range("P" & GroupNumber)
Else
Range("D" & GroupNumber).Copy Destination:=Range("Q" & GroupNumber)
End If
End If
End If
Next oOption
End Sub
Test Results:
I have set up three arrays in Word. The arrays are as follows:
tacData = Array("32064600", "33001000", "33001100", "33002400", "33003000", "33002400", "35011001", "35013200", "35124100", "35124100")
makeData = Array("Alcatel", "Alcatel", "Sagem", "Samsung", "AEG Mobile", "Samsung", "Nokia", "Maxon", "Siemes", "Nokia")
modelData = Array("One Touch EasyHD", "91009109MB2", "RC410G14", "SGH-200", "Sharp TQ6", "SGH-5300", "DCT-3", "MX6832", "MC399 Cellular Termnial", "DCT-4")
I have made a user form which get a TAC (Value) from the User. Can I get this value and search for it in the first array and get its ID so that I can get the make and model from the other two arrays? I have tried using some code samples that I found but they do not seem to work with Word throwing errors. They were things like Application.Match.
On a side note, would there be a better way to store this information rather than three arrays?
I think you need a collection object. Look at the code below
Dim tacData() As Variant, makeData() As Variant, modelData() As Variant
tacData = Array("32064600", "33001000", "33001100", "33002400", "33003000", "33002401", "35011001", "35013200", "35124100", "35124101")
makeData = Array("Alcatel", "Alcatel", "Sagem", "Samsung", "AEG Mobile", "Samsung", "Nokia", "Maxon", "Siemes", "Nokia")
modelData = Array("One Touch EasyHD", "91009109MB2", "RC410G14", "SGH-200", "Sharp TQ6", "SGH-5300", "DCT-3", "MX6832", "MC399 Cellular Termnial", "DCT-4")
Dim i As Integer, N As Integer
N = UBound(tacData, 1) 'Get the data size
Dim item As Phone 'Temp variable for creating elements into a collection
Dim list As New VBA.Collection 'Define a new collection
For i = 1 To N
Set item = New Phone 'Assign a new Phone object
With item
.TAC = tacData(i) 'Assign values to the phone
.Make = makeData(i)
.Model = modelData(i)
End With
list.Add item, item.TAC 'Add the phone to the list with a KEY
Set item = Nothing
Next i
Dim TAC As String
TAC = "33002400" 'get user input
Set item = list(TAC) '** lookup Phone using Key **
If Not item Is Nothing Then ' Show results
Debug.Print item.TAC, item.Make, item.Model
Else
Debug.Print "Not Found"
End If
It works with a new class called 'Phone' containing
Option Explicit
Public TAC As String
Public Make As String
Public Model As String
and inserted into VBA via this menu item, and renaming in the project tree as "Phone"
The requirement is that the 'TAC' code is unique. In your case it wasn't and I had to change some numbers to make them unique. How have to consider what to do if in real life there are multiple phones with the same TAC code.
PS. Welcome to the world of object oriented programming. This was your first step.
i have 50 checkboxes for 50 american states. The user can choose all 50 or only 1( so basically any number he wants). Based on his choice, I want to insert or update the table in sql server 2008. e.g-
Color = blue and chk1=check, chk2= check and chk3 = check (chk = checkbox). now the user wants to ad 10 more states to this or remove these 3 and add 5 more. so u basically get the idea. the table in database looks like this - ID Color State_id there is a table called states, so stateid shall come from there. so how do i do a loop insert or update in vb.net?
I would use a data source and a checkboxlist. You already have your states in a datatable, populate a checkboxlist with a databound selection from a SqlDataSource (or datatable of your own choosing). Then when you click your button just iterate through the following loop:
Dim dt as New myTypedDataTable ' constructed from datasource
Dim color as String = "Blue" ' Filled however you set color
For Each item As ListItem In Me.CheckBoxList1.Items
If item.Selected Then
Dim row as myTypedDataTableRow = dt.NewmyTypedDataTableRow
row.Color = color
row.State_id = item.Value
dt.Rows.Add(row)
End If
Next
Once you've got the datatable filled with the rows in question you could either use the SqlDataSource to perform an insert operation or perform the insert operation atomically. There are several ways to accomplish it, but this is probably the simplest way to iterate through the items given the data structure you described.
In this context, I sometime go the easy way and delete all the user items store in the database and then only do insert.
This can be a problem if you have for example a insert_date. In this case, you'll need to list of user selected options. Loop in the new list, if the item is not found in the old list then it's an insert. Loop in the old list, if the item is not found in the new list then it's a delete.
I would use bitwise operation and a long variable in .net (mixed with an enum for the flag)
one field in the db and way easier to play with what the user select
small sample
Enum state As Long '64 enum maxium since long = 64 bits
ALABAMA = 1
ALASKA = 2
NEVADA = 4
ARIZONA = 8
ARKANSAS = 16
CALIFORNIA = 32
COLORADO = 64
CONNECTICUT = 128
DELAWARE = 256
'etc etc etc
End Enum
Module Module1
Sub Main()
Dim userselect As state = 0
Console.WriteLine("your checked box state")
Console.WriteLine("in this case im using the order of the enum for selecting")
Dim checkbox = New Boolean() {True, False, False, True, False, False, True, False, False}
For i = 0 To checkbox.Length - 1
userselect = CType(userselect + If(checkbox(i), (2 ^ (i + 1)), 0), state)
Next
For Each s As state In [Enum].GetValues(GetType(state))
If (userselect And s) > 0 Then
Console.WriteLine("selected " & s.ToString)
End If
Next
Console.WriteLine("Value of userselect is " & userselect.ToString)
Console.ReadKey()
End Sub
End Module
OUTPUT:
selected NEVADA
selected ARIZONA
selected COLORADO
Value of userselect is 76