I m trying to find out array index using visual basic. I tried some code with VB.Net and getting correct output. Below is the code I am using,
Dim FindThisString as String="EFGH"
Dim MyArray() As String={"ABCD","EFGH","IJKLM"}
For Each Str As String In MyArray
If Str.Contains(FindThisString) Then
MsgBox(Str.IndexOf(FindThisString))
End If
Next
Now I want to try the same method with VB 6.0. I am using Instr function but it is giving me string index in entire string and I am looking for array index i.e. index of string "EFGH" in MyArray.
Here is the VB6 code I'm trying:
Dim MyString as String
Dim str as Variant
MyString="ABCD/EFGH/IJKLM"
Dim MyArray() as String
MyArray = split(MyString,"/")
Dim inIndex as Integer
For Each Str In MyArray
inIndex= Instr(str,"EFGH")
MsgBox inIndex
Next
You would basically use the same algorithm:
Loop through the array (you'll need to use a Variant as the loop variable for VB Classic For Each),
verify if the array entry contains the substring in question (you need to use InStr here, since VB Classic does not have String.Contains),
return the index (which you already determined with InStr).
The implementation is left as an exercise.
Function IndexOf(ByRef arr() As String, ByVal str As String) As Integer
Dim joinedStr As String
Dim strIndex As Integer
joinedStr = "|" & Join(arr, "|")
strIndex = InStr(1, joinedStr, str)
If strIndex = 0 Then
IndexOf = -1
Exit Function
End If
joinedStr = Mid(joinedStr, 1, strIndex - 1)
IndexOf = UBound(Split(joinedStr, "|")) - 1
End Function
Related
Let's say I have the following Array, arr that contains a maximum of 20 substrings. In this example, the array will have 4 substrings:
arr = {"AAAA: 1234567" , "BBBB: 2345678" , "CCCC: 98765432" , "DDDD: 87654321"}
Note: Capitalization is not important.
I am needing assistance with finding a substring inside an array (again, up to 20 strings possible), that Starts With CCCC:, and then assigning that entire string to it's own variable, let's call it Var1.
I understand I could assign Var1 = arr(2), but I need to figure out how to determine the index number in the array that meets my criteria.
What I would really appreciate (although any method I will be happy with), is making a stand alone function such as:
Function ArrayIndex(ArrayInput as Variant, StartsWith as String) as Byte
'Arguments Here
End Function
Then I could just use this in my Subroutine:
Var1 = arr(ArrayIndex(arr, "CCCC:"))
Update 1
Here is a snippet of my current code
Sub T_Report
'<Shortcut = Shift+Ctrl+T>
Dim Data as String, DataArray as Variant
With ActiveSession
.Copy 0, 2, 80, 21 'Just a big block of text with multiple lines, copied to clipboard
Data = Clipboard 'Set Data to the clipboard value
DataArray = Split(Data,vbCrLf) 'This is "Data" in an Array, separated by line breaks
'Just checking to see if the Array was successful (it is)
Debug.Print DataArray(0) & vbNL & DataArray(1) & vbNL & DataArray(2) & _
vbNL & DataArray(3) & vbNL & DataArray(4) & vbNL & vbNL
'Misc code here
Dim sF1 as String, sF2 as String, sF3 as String
Dim Rslt1 as String, Rslt2 as String, Rslt3 as String
sF1 = "Field1:"
sF2 = "Field2:"
sF3 = "Field3:"
MsgBox DataArray(0) ' This works fine, giving me first substring
Rslt1 = FindMyString(sF1, DataArray)
' Misc Code
End With
End Sub
However, when I use the following function, I get Type Mismatch error on the MsgBox arr(0) line, although it should be giving me the very first substring of DataArray in the above sub (should be an exact match, the array has not been modified).. However, when I do MsgBox DataArray(0) above, I do get the first substring.
Private Function FindMyString(strToFind As String, ParamArray arr() As Variant) As String
Dim i As Integer
Dim iLen As Integer
Dim strArr As String
FindMyString = "" ' Returns Blank String if not found
' I get type mismatch here (Doesn't appear Array from sub loaded into this function)
MsgBox arr(0)
iLen = Len(strToFind)
For i = 0 To UBound(arr)
strArr = CStr(arr(i))
If strToFind = Left$(strArr, iLen) Then
FindMyString = strArr
Exit Function
End If
Next i
End Function
EDIT - FIX YOUR ARRAY LOAD
Change this (it MUST give you an error!):
arr = {"AAAA: 1234567" , "BBBB: 2345678" , "CCCC: 98765432" , "DDDD: 87654321"}
To This:
Dim arr As Variant
arr = Split("AAAA: 1234567,BBBB: 2345678,CCCC: 98765432,DDDD: 87654321", ",")
If you want to use a function to do your bidding you can pass an array of data using the ParamArray type. It has to be the last parameter in your function
This should do what you want:
Private Function FindMyString(strToFind as string, ParamArray arr() As Variant) As String
Dim i As Integer
Dim iLen as Integer
Dim strArr as String
FindMyString = "" ' Returns Blank String if not found '
Debug.Print arr(0)(0) ' Print first element of array
iLen = Len(strToFind)
For i = 0 To UBound(arr(0))
strArr = CStr(arr(0)(i))
If strToFind = Left$(strArr, iLen) Then
FindMyString = strArr
Exit Function
End If
Next i
End Function
In your example you can test it by:
Var1 = FindMyString("CCCC:", arr)
I'm using VBA but not on excel.
I know that on VBA for Excel, you could do something like Split("String will be splitted") and obtain an array back.
Is there a way to perform the split without this function? Because it isn't recognize by the version of VBA I'm using.
Thank you.
something like this, returning a collection, for time as didn't want to code all the if's for redimming the o/p array.
Public Sub testing()
Dim c As New Collection
Set c = New_Split("test split function", " ")
End Sub
Public Function New_Split(strInput As String, strDelimiter As String) As Collection
Dim colDelimitPoints As New Collection
Dim intCounter As Integer
Dim intPrevPoint As Integer
For intCounter = 1 To Len(strInput)
If Mid(strInput, intCounter, 1) = strDelimiter Then
colDelimitPoints.Add intCounter, CStr(intCounter)
End If
Next intCounter
intPrevPoint = 1
Set New_Split = New Collection
For Each i In colDelimitPoints
New_Split.Add Mid(strInput, intPrevPoint, (i - intPrevPoint))
intPrevPoint = i + 1
Next i
End Function
You can combine the collection creation and the iteration of it later into one routine, I've left separate to show how it's working.
I am assuming you are using an early version of Excel in which Split doesn't exist, #Meehow and #Nathan_Sav are correct that you are best off writing your own, I using commands like mid, and instr.
There is not an equivalent, just a way to make an equivalent.
See the below equivalent: -
Public Sub Sample()
Dim ArySplit() As String
ArySplit = FnSplit("This|is|my||string", "|")
End Sub
Private Function FnSplit(ByVal StrContent As String, ByVal StrDelimiter As String) As String()
Dim AryTemp() As String
ReDim AryTemp(0)
'Work until we have nothing left to work with
Do Until StrContent = ""
'Only increase the array size if needed
If AryTemp(UBound(AryTemp, 1)) <> "" Then ReDim Preserve AryTemp(UBound(AryTemp, 1) + 1)
'if the delimiter is no longer there then output the remaining content
'and clear out the todo string
If InStr(1, StrContent, StrDelimiter) = 0 Then
AryTemp(UBound(AryTemp, 1)) = StrContent
StrContent = ""
Else
'If there is a delimiter then then add it to the array and take it and the delimiter
'off of the to do string
AryTemp(UBound(AryTemp, 1)) = Left(StrContent, InStr(1, StrContent, StrDelimiter) - 1)
StrContent = Right(StrContent, Len(StrContent) - ((InStr(1, StrContent, StrDelimiter) - 1) + Len(StrDelimiter)))
End If
Loop
'Return our array
FnSplit = AryTemp
End Function
I'm trying to loop through a listbox and add the contents to an array....
My code is this:
Private Sub exportfolders_Click()
Dim list As String
Dim folderlist As String
Dim folderarray() As String
'Dim i As Interger
For i = 0 To Me.selectedfolders.ListCount - 1
'folderlist = (Me.selectedfolders.Column(0, i))
'folderarray() = Join(Me.selectedfolders.Column(0, i), ",")
list = (Me.selectedfolders.Column(0, i))
folderarray() = Join(list, ",")
ReDim Preserve folderarray(i)
Next i
folderlist = folderarray
'folderarray() = Join(folderlist, ",")
MsgBox (folderlist)
End Sub
You can see the bits I have commented out, trying all sorts to get it to work. But I keep getting the message "Can't assign to array" at folderarray(i) = Join(list, ","). Any pointers as to where I am failing?
You can concatenate the list box items into a string, and then use Split() to load your array. That way, the array is sized automagically without you needing to ReDim.
I tested this code in Access 2010:
Dim folderarray() As String
Dim i As Long
Dim strList As String
For i = 0 To Me!selectedfolders.ListCount - 1
strList = strList & "," & Me!selectedfolders.Column(0, i)
Next
' use Mid() to exclude the first comma ...
folderarray = Split(Mid(strList, 2), ",")
Note I don't know what you want to do with the array after loading it. MsgBox folderarray would throw Type mismatch error. MsgBox Mid(strList, 2) would be valid, but if that's what you want, you wouldn't need the array.
1) declare the array. Take a look at https://msdn.microsoft.com/en-us/library/wak0wfyt.aspx
2) No need of support variable
3) Assign the values to your array with the correct syntax
Private Sub exportfolders_Click()
Dim folderarray() As String
Dim i As Interger
Redim folderarray (Me.selectedfolders.ListCount-1)
For i = 0 To Me.selectedfolders.ListCount - 1
folderarray(i) = Me.selectedfolders.Column(0, i)
Next i
' Write here what you want to do with your array
End Sub
You could try something like this:
Private Sub ListToArray()
Dim folderArray() As Variant
Dim currentValue As String
Dim currentIndex As Integer
Dim topIndex As Integer
topIndex = Me.selectedfolders.ListCount - 1
ReDim folderArray(0 To topIndex, 0 To 1)
For i = 0 To topIndex
currentValue = Me.selectedfolders.Column(0, i)
folderArray(i, 0) = i
folderArray(i, 1) = currentValue
Next i
End Sub
Note my example is a multi-dimensional array which will give you the ability to add more than one item should you chose to do so. In this example I added the value of "i" as a placeholder/ index.
I reviewed this question/answer here before writing this: Declare and Initialize String Array in VBA
I am trying to understand the proper way to declare and initialize an array WITHOUT resorting to data type VARIANT.
This is my code, and it does work as it is:
Function MakeLegalFilename(legalname As String) As String
Dim MyArray() As Variant
Dim x As Integer
MyArray = Array("<",">","?","#","%")
For x = LBound(MyArray) To UBound(MyArray)
legalname = Replace(legalname, MyArray(x), "", 1)
Next x
MakeLegalFilename = legalname
End Function
If I change "Variant" to "String," the code fails at MyArray = Array(... with a runtime error 13 type mismatch.
If I define the array size to match the number of characters in the string (5 total, but array starts at 0):
Dim MyArray(4) As String
MyArray = Array("<",">","?","#","%")
Now I get a compile error at MyArray = Array(... that says "Can't assign to array."
I know that I could declare the array this way and make it work (I tested it this way):
MyArray(0) = "<"
MyArray(1) = ">"
MyArray(2) = "?"
...
MyArray(4) = "%"
But if I am coding in a whole list of characters (say 20), then doing this is cumbersome, and plus, I would like to know why the other way doesn't work, since it suggests I have a fundamental misunderstanding. In it's most basic form, my question really is, why doesn't this:
Dim MyArray(4) As String
MyArray = Array("<",">","?","#","%")
work?
Thank you.
Array returns a Variant.
So you can't use it if you don't what a variant.
Split can split a string.
Split Function
Description
Returns a zero-based, one-dimensional array containing a specified number of substrings.
Syntax
Split(expression[, delimiter[, limit[, compare]]])
Put comma delimited string into split containing your characters.
Use a helper function:
Dim MyArray() As String
MyArray = StrArray("<", ">", "?", "#", "%")
...
Public Function StrArray(ParamArray args() As Variant) As String()
Dim i As Long
ReDim temp(UBound(args)) As String
For i = 0 To UBound(args)
temp(i) = args(i)
Next
StrArray = temp
End Function
To initialize static-size string array, use:
Dim MyArray(4) As String
MyArray(0) = "<"
MyArray(1) = ">"
MyArray(2) = "?"
MyArray(3) = "#"
MyArray(4) = "%"
To initialize dynamic-size string array, use:
Dim MyArray() As String
For i = 0 to 10
Redim Preserve MyArray(i) 'increase the size
MyArray(i) = Char(64 + i)
Next
For further information, please see: http://msdn.microsoft.com/en-us/library/wak0wfyt.aspx
Here's my code so far:
Dim i As Integer
Dim stringArray() as String
stringArray = split("Hello|there", "|")
For i = 0 To stringArray.Length()
' Logic goes here
Next
VB6 doesn't seem to like me using stringAray.Length() and gives me a compile error message like Invalid Qualifier, but what's the right way to iterate through each element of a string array?
ubound() returns the upper bounds;
Dim i As Long
Dim stringArray(1) as String
stringArray(0) = "hello"
stringArray(1) = "world"
For i = 0 To ubound(stringArray)
msgbox(stringArray(i))
Next
Dim i As Integer
Dim stringArray() as String
stringArray = split("Hello|there", "|")
For i = 0 To ubound(stringArray)
' Logic goes here
Next
This is the coding for above questions.
I have re do and also include the output using Visual Basic 6.0
it is pretty simple and easy to understand.
However,I wanted to try for more iteration.
click here for the coding and the output