Using Variables as module/array names - arrays

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

Related

if the same item in all four comboboxes are chosen

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

How do I sort an array of different times?

So I have an array of various timeslots, but I want to sort out the times from the earliest ones to the latest ones, however, I also want to delete any elements within the array that has the time value of 12:00am.
Appointment(0) = #10:45:00 AM#
Appointment(1) = #12:00:00 AM# 'My actual has up 80 elements of different timeslots but I'm using 3 elements as an example
Appointment(2) = #12:00:00 AM#
Is there anyone who can help me with this problem?
Using a string array is not a good idea if that's what you used just use a list of DateTime and the Sort method.
Dim list As List(of DateTime) = new List(of DateTime)
For Each val As String In Appointment
list.Add(val.replace(" ",""))
Next
list.Sort(New Comparison(Of Date)(Function(x As Date, y As Date) y.CompareTo(x)))
Nothing in .Net for removing specific items from array, but it can be "simplified" a bit with LINQ:
Dim Appointment = {#10:45#, #12AM#, #12AM#}
Appointment = (From a In Appointment Where a <> #12AM# Order By a).ToArray
or
Appointment = Appointment.Except({#12AM#}).ToArray
Array.Sort(Appointment)
A bit more efficient alternative can be to use generic collection like List or SortedSet instead:
Dim list = New List(Of Date) From {#10:45#, #12AM#} ' or Dim list = Appointment.ToList
list.Add(#12AM#)
list.RemoveAll(Function(a) a = #12AM#)
list.Sort()

Need help looping through groups of option buttons while copy/past cell contents

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:

Searching an Array in Word (Visual Basic for Applications)

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.

how to save multiple checkbox values in one while or for loop in vb.net

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

Resources