how to store multiple textbox values in array - vba

I have 5 textbox and in each I have to write the values, and all the value I want to store in to and array.
this what i did
Dim arrayNames() As String = {CDec(txtName1.Text), CDec(txtName2.Text), CDec(txtName3.Text), CDec(txtName4.Text), CDec(txtName5.Text)}

Use the Array function with a known set of items, as Victor notes in the comments:
Dim myArray() As String
myArray = Array(TextBox1.Value, TextBox2.Value, TextBox3.Value)
If you need to add dynamically to the array, then you can use ReDim Preserve statement, which resizes the array and preserves existing values:
Dim myArray() As String
myArray = Array(TextBox1.Value, TextBox2.Value, TextBox3.Value)
'later, add another element to the array:
ReDim Preserve myArray(Ubound(myArray)+1)
myArray(UBound(myArray)) = TextBox4.Value

Related

Create Items through splitting a string by comma(,) and add them to the collection

I have a collection called as SheetNameCollection and I have a string called as SheetNames.
Here goes my code,
Dim SheetNames As String
Dim SheetNameCollection As Collection
Set SheetNameCollection = New Collection
SheetNames = "wk1,wk2,wk3,wk4"
'This is dynamic and will usually be more than 100 sheets.
I am looking for a way to add these SheetNames one by one into my collection SheetNameCollection.
Kindly suggest an approach. Thanks.
As Scott Craner pointed out.
Split the names into an array and then iterate over each name in the array adding it to the collection.
Dim item As Variant
For Each item In Split(SheetNames, ",")
SheetNameCollection.Add item
Next

Creating a new String Array from another

I have an array of integers (dfArray) and would like to create a new second String array which consists of the integers and appending "G" to the beginning. What's the best way to go about this? I was thinking of For Each but couldn't get it to work. Thanks in advance.
Set dfArray = [dff]
Set dfArray2 = ["G" & dff] 'incorrect but you get the idea?
Dim dfArray() As Variant
Dim dfArray2() As String
dfArray = [dff].Value
ReDim dfArray2(UBound(dfArray)) As String
Dim i As Double
For i = 1 To UBound(dfArray) Step 1
dfArray2(i) = "G" & dfArray(i, 1)
Next i
Anyways, from my personal point of view, I don't like to asign a complete Range into Array, only if needed. I prefer to loop using Lbound or Ubound and control the array all the time. To asign a range into an Array, you need the Array variable to be Variant type, and also, you can't use Preserve easily. Check this question for more info
Issues about Variant Arrays

build an array of integers inside a for next loop vb.net

i got this far ... my data string, "num_str" contains a set of ~10 numbers, each separated by a comma. the last part of the string is a blank entry, so i use '.Trim' to avoid an error
Dim i As Integer
Dim m_data() As String
m_data = num_str.Split(",")
For i = 0 To UBound(m_data)
If m_data(i).Trim.Length > 0 Then
MsgBox(Convert.ToInt32(m_data(i).Trim))
End If
Next i
as you can see from the Msgbox, each of the numbers successfully pass through the loop.
where i am stuck is how to place all of the 'Convert.ToInt32(m_data(i).Trim)' numbers, which are now presumably integers, into an array.
how do i build an array of integers inside the For / Next loop so i can find MAX and MIN and LAST
TIA
You just need to initialize the array with the zero-based indexer. You can deduce it's initial size from the size of the string():
Dim m_data = num_str.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Dim intArray(m_data.Length) As Int32
For i = 0 To m_data.Length - 1
intArray(i) = Int32.Parse(m_data(i).Trim())
Next i
Note that i've also used the overload of String.Split which removes empty strings.
This way is more concise using the Select LINQ Operator.
Dim arrayOfInts = num_str.
Split({","c},
StringSplitOptions.RemoveEmptyEntries).
Select(Function(v) Int32.Parse(v.Trim()))
Dim minInt = arrayOfInts.Min()
Dim maxint = arrayOfInts.Max()

Add new value to integer array (Visual Basic 2010)

I've a dynamic integer array to which I wish to add new values. How can I do it?
Dim TeamIndex(), i As Integer
For i = 0 to 100
'TeamIndex(i).Add = <some value>
Next
Use ReDim with Preserve to increase the size of array with preserving old values.
ReDim in loop is advisable when you have no idea about the size and came to know for increasing the Array size one by one.
Dim TeamIndex(), i As Integer
For i = 0 to 100
ReDim Preserve TeamIndex(i)
TeamIndex(i) = <some value>
Next
If you to declare the size of array at later in code in shot then use
ReDim TeamIndex(100)
So the code will be :
Dim TeamIndex(), i As Integer
ReDim TeamIndex(100)
For i = 0 to 100
TeamIndex(i) = <some value>
Next
You can Use the ArrayList/List(Of T) to use Add/Remove the values more dynamically.
Sub Main()
' Create an ArrayList and add three strings to it.
Dim list As New ArrayList
list.Add("Dot")
list.Add("Net")
list.Add("Perls")
' Remove a string.
list.RemoveAt(1)
' Insert a string.
list.Insert(0, "Carrot")
' Remove a range.
list.RemoveRange(0, 2)
' Display.
Dim str As String
For Each str In list
Console.WriteLine(str)
Next
End Sub
List(Of T) MSDN
List(Of T) DotNetperls
There is nothing in Romil's answer that I consider to be wrong but I would go further. ReDim Preserve is a very useful command but it is important to realise that it is an expensive command and to use it wisely.
Consider:
Dim TeamIndex(), i As Integer
For i = 0 to 100
ReDim Preserve TeamIndex(i)
TeamIndex(i) = <some value>
Next
For every loop, except i=0, the Common Language Runtime (CLR) must:
find space for a new integer array that is one element bigger than the previous array
copy the values across from the previous array
initialise the new element
release the previous array for garbage collection.
ArrayList is fantastic if you need to add or remove elements from the middle of the array but you are paying for that functionality even if you do not need it. If, for example, you are reading values from a file and storing them sequentially but do not know in advance how many values there will be, ArrayList carries a heavy overhead you can avoid.
I always use ReDim like this:
Dim MyArray() As XXX
Dim InxMACrntMax As Integer
ReDim MyArray(1000)
InxMACrntMax=-1
Do While more data to add to MyArray
InxMACrntMax = InxMACrntMax + 1
If InxMACrntMax > UBound(MyArray) Then
ReDim Preserve MyArray(UBound(MyArray)+100)
End If
MyArray(InxMACrntMax) = NewValue
Loop
ReDim MyArray(InxMACrntMax) ' Discard excess elements
Above I have used 100 and 1000. The values I pick depend on my assessment of the likely requirement.

String Array Thing!

Right - to start with, I'm entering unfamiliar areas with this - so please be kind!
I have a script that looks a little something like this:
Private Function checkString(ByVal strIn As String) As String
Dim astrWords As String() = New String() {"bak", "log", "dfd"}
Dim strOut As String = ""
Dim strWord As String
For Each strWord In astrWords
If strIn.ToLower.IndexOf(strWord.ToLower, 0) >= 0 Then
strOut = strWord.ToLower
Exit For
End If
Next
Return strOut
End Function
It's function is to check the input string and see if any of those 'astrWords' are in there and then return the value.
So I wrote a bit of code to dynamically create those words that goes something like this:
Dim extensionArray As String = ""
Dim count As Integer = 0
For Each item In lstExtentions.Items
If count = 0 Then
extensionArray = extensionArray & """." & item & """"
Else
extensionArray = extensionArray & ", ""." & item & """"
End If
count = count + 1
Next
My.Settings.extensionArray = extensionArray
My.Settings.Save()
Obviously - it's creating that same array using list items. The output of that code is exactly the same as if I hard coded it - but when I change the first bit of code to:
Dim astrWords As String() = New String() {My.Settings.extensionArray}
instead of:
Dim astrWords As String() = New String() {"bak", "log", "dfd"}
It starts looking for the whole statement instead of looping through each individual one?
I think it has something to do with having brackets on the end of the word string - but I'm lost!
Any help appreciated :)
When you use the string from the settings in the literal array, it's just as if you used a single strings containing the delimited strings:
Dim astrWords As String() = New String() {"""bak"", ""log"", ""dfd"""}
What you probably want to do is to put a comma separated string like "bak,log,dfd" in the settings, then you can split it to get it as an array:
Dim astrWords As String() = My.Settings.extensionArray.Split(","C)
You need to set extensionArray up as a string array instead of simply a string.
Note that
Dim something as String
... defines a single string, but
Dim somethingElse as String()
... defines a whole array of strings.
I think with your code, you need something like:
Dim extensionArray As String() = new String(lstExtensions.Items)
Dim count As Integer = 0
For Each item In lstExtentions.Items
extensionArray(count) = item
count = count + 1
Next
My.Settings.extensionArray = extensionArray
My.Settings.Save()
Then at the start of checkString you need something like
Private Function checkString(ByVal strIn As String) As String
Dim astrWords As String() = My.Settings.extensionArray
...
There also might be an even easier way to turn lstExtentions.Items into an Array if Items has a 'ToArray()' method, but I'm not sure what Type you are using there...
What you've done is created a single string containing all 3 words. You need to create an array of strings.
New String() {"bak", "log", "dfd"}
means create a new array of strings containing the 3 strings values "bak", "log" and "dfd".
New String() {My.Settings.extensionArray}
means create a new array of strings containing just one value which is the contents of extensionArray. (Which you have set to ""bak", "log", "dfd""). Note this is one string, not an array of strings. You can't just create 1 string with commas in it, you need to create an array of strings.
If you want to create your array dynamically, you need to define it like this:
Dim astrWords As String() = New String(3)
This creates an array with 3 empty spaces.
You can then assign a string to each space by doing this:
astrWords(0) = "bak"
astrWords(1) = "log"
astrWords(2) = "dfd"
You could do that bit in a for loop:
Dim count As Integer = 0
For Each item In lstExtentions.Items
astrWords(count) = item
count = count + 1
Next
Alternatively, you could look at using a generic collection. That way you could use the Add() method to add multiple strings to it
I think you want your extensionArray to be of type String() and not String. When you are trying to initialize the new array, the initializer doesn't know to parse out multiple values. It just sees your single string.