I tried to concat some strings in Excel with VBA.
Sub Button1_Click()
Dim lenArray As Variant
Dim strArray As Variant
Dim strCombined As String
Dim space As String
lenArray = Range("D1:J1").Value
strArray = Range("D2:J2").Value
space = " "
Dim i As Integer
Dim temp As String
For i = LBound(strArray) To UBound(strArray)
strCombined = strCombined & strArray(i)
temp = WorksheetFunction.Rept(space, CInt(lenArray(i)) - Len(strArray(i)))
strCombined = strCombined & temp
Next i
Range("B4").Value = strCombined
End Sub
However, it always gives me out of bound error.
I also tried changing
For i = LBound(strArray) To UBound(strArray)
to
For i = 1 To 7
or
For i = 1 To 2
but it never works.
I have tried to iterate only the strArray with For Each and it would work.
Any help would be great.
Edited:
The spreadsheet I am using
Related
This is a follow up question to my previous VBA question. Someone provided me with a potential solution for a lag in performance, and mentioned instead of looping through the actual cells in each column, transform the columns into Arrays and then load the results into a new Array.
I keep getting "subscript out of range" issues, among other various errors. I've manipulated these Arrays so many times with ReDim and others to try to load the results, but I keep hitting the same issue. You will see some of the code I tried where things are commented out.
How can I properly load these results based on the information I have? I thought at first it was because I was declaring a dynamic, empty Array, so that's why I used the UBound of an array of the same size in a ReDim.
Sub Missing_CAT():
Dim i As Variant
Dim j As Variant
'Dim j As Long
'Dim h As Long
'Dim h As Variant
Dim d As Date
Dim e As Date
Dim f As Date
Dim a As String
Dim ws As Worksheet
Dim rowCount As Long
Dim secondRowCount As Long
Dim oDateArr() As Variant
Dim fromDateArr() As Variant
Dim toDateArr() As Variant
Dim perilArr() As Variant
Dim resultArr() As Variant
Dim cell As Variant
Dim counter As Variant
Dim count As Long
Dim boundary As Long
Dim ub As Integer
rowCount = Worksheets("raw_data_YOA").Cells(Rows.count, "A").End(xlUp).row
oDateArr = Sheets("raw_data_YOA").Range("Q2:Q" & rowCount).Value
ub = UBound(oDateArr)
ReDim resultArr(ub)
count = 0
'For i = 2 To rowCount
For Each i In oDateArr
'd = Worksheets("raw_data_YOA").Cells(i, 17).Value
d = i
For Each ws In Sheets
If ws.Name = "2020" Or ws.Name = "2019" Then
secondRowCount = ws.Cells(Rows.count, "D").End(xlUp).row
fromDateArr = ws.Range("D5:D" & secondRowCount).Value
toDateArr = ws.Range("E5:E" & secondRowCount).Value
perilArr = ws.Range("F5:F" & secondRowCount).Value
' For j = 5 to secondRowCount
'For Each j In fromDateArr
'boundary = UBound(fromDateArr)
For j = 1 To UBound(fromDateArr)
' MsgBox (fromDateArr(j))
e = fromDateArr(j, 1)
f = toDateArr(j, 1)
p = perilArr(j, 1)
'e = ws.Cells(j, 4).Value
' f = ws.Cells(j, 5).Value
If d >= e And d <= f Then
' ReDim Preserve resultArr(1 To UBound(resultArr) + 1)
' resultArr(UBound(resultArr), 1) = p
resultArr(count) = p
Exit For
ElseIf j = UBound(fromDateArr) Then
' Worksheets("raw_data_YOA").Cells(i, 63).Value = "FALSE"
' ReDim Preserve resultArr(1 To UBound(resultArr) + 1)
' MsgBox (UBound(resultArr))
resultArr(count) = "FALSE"
End If
Next j
Else
GoTo NextIteration
End If
count = count + 1
NextIteration:
Next
Next i
counter = 0
For Each cell In Sheets("raw_data_YOA").Range("Q2:Q" & rowCount)
cell.Value = resultArr(counter)
counter = counter + 1
Next
MsgBox ("Done")
End Sub
EDIT:
Specifically, the lines throwing the errors are resultArr(count) = ...
so what I need to do is fill an array using an InputBox, then but that in an array, sort it alphabetically and then output it to the current word document. I have it almost most complete, the issue is it is only outputting the last word to the document. Im guessing my loop is wrong but I cannot find VBA documentation to do this to save my life. Thank you
Option Explicit
This is the main sub that declares the array
Sub Main()
Dim ListArr() As String
ListArr = Get_Input_List()
Call Bubble_Sort_Ascending(ListArr)
Call Output_List_To_Document(ListArr)
End Sub
Function to get input and fill array
Function Get_Input_List() As String()
Dim list As String
list = InputBox("Please enter words to sort separated with a comma and no spaces", "Words")
Get_Input_List = Split(list, ",")
End Function
Sorts the array alphabetically
Sub Bubble_Sort_Ascending(listNewArray() As String)
Dim SrtTemp As Variant
Dim inputWord As Variant
Dim i As Long
Dim j As Long
'Alphabetize Sheet Names in Array List
For i = LBound(listNewArray) To UBound(listNewArray)
For j = i To UBound(listNewArray)
If listNewArray(i) > listNewArray(j) Then
SrtTemp = listNewArray(j)
listNewArray(j) = listNewArray(i)
listNewArray(i) = SrtTemp
End If
Next j
Next i
End Sub
This is the problem, I cannot output the whole array to the word document. I have found plenty of documentation on how to do this into an excel spreadsheet but almost nothing for word.
Sub Output_List_To_Document(newListArray() As String)
Dim inputWord As Variant
Dim i As Long
Dim j As Long
For i = LBound(newListArray) To UBound(newListArray)
For j = i To UBound(newListArray)
For Each inputWord In newListArray
ActiveDocument.Range = inputWord & vbCrLf
Next
Next j
Next i
End Sub
You're over-writing ActiveDocument.Range each time through the loop. If you want to append to the end of it, you need to collapse the range to it's ending position:
Sub Output_List_To_Document(newListArray() As String)
Dim inputWord As Variant
Dim i As Long
Dim j As Long
Dim insertPos As Range
Set insertPos = ActiveDocument.Range
For i = LBound(newListArray) To UBound(newListArray)
For j = i To UBound(newListArray)
For Each inputWord In newListArray
insertPos.Collapse wdCollapseEnd
insertPos = inputWord & vbCrLf
Next
Next j
Next i
End Sub
Note - It isn't clear why you're looping through the array with 3 nested loops. If you only need to write each word once, I suspect you're really looking for something more like this:
Sub Output_List_To_Document(newListArray() As String)
Dim insertPos As Range
Set insertPos = ActiveDocument.Range
Dim inputWord As Variant
For Each inputWord In newListArray
insertPos.Collapse wdCollapseEnd 'Value 0, Can ignore writing it as well
insertPos = inputWord & vbCrLf
Next
End Sub
I have the code below to get the value assigned to Array "UIDList()". But for what ever reason it is only getting the last value only. Can you please correct what could've been gone wrong.
Dim strTest As String
Dim strarray() As String
Dim UIDList() As String
Dim intCount As Integer
Dim TotUID As Integer
Set oFS = oFSO.OpenTextFile("C:\Pro\test.txt")
txtpro = oFS.ReadAll
strTest = txtpro
strarray = Split(strTest, "=")
For intCount = LBound(strarray()) To UBound(strarray())
If InStr(strarray(intCount), "NAME") Then
UIDList() = Split(strarray(intCount), "NAME")
End If
Next
For TotUID = LBound(UIDList()) To UBound(UIDList())
Debug.Print UIDList(TotUID)
Next
Improper nesting:
change to this:
For intCount = LBound(strarray()) To UBound(strarray())
'Erase the array
Erase UIDList
If InStr(strarray(intCount), "NAME") Then
UIDList() = Split(strarray(intCount), "NAME")
End If
'/ Check if UIDList() has any elements
If Not (Not UIDList()) Then
For TotUID = LBound(UIDList()) To UBound(UIDList())
Debug.Print UIDList(TotUID)
Next
End If
Next
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'm looking for a little guidance and experience. I have an VBA module that creates two strings. See below. I want to use an array to compare the two stings and write the successful matches or "no match" for the element to a third array or directly to the worksheet.
The second part of this is a "percent of" match of Arr2 to Arr1. So the below example would be 88%.
> Arr1 result
> 726741,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X
> Arr2 result
> 726742,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X
Any advice would be great.
Here is one way to accomplish the task using simple for loops.
Sub compareStrings()
Dim str1 As String
Dim str2 As String
str1 = "726741,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X"
str2 = "726742,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X"
Dim Arr1 As Variant
Dim Arr2 As Variant
Dim ArrResults As Variant
Arr1 = Split(str1, ",")
Arr2 = Split(str2, ",")
Dim countMatches As Integer
countMatches = 0
ReDim ArrResults(UBound(Arr1))
For i = LBound(Arr1) To UBound(Arr1)
If Arr1(i) = Arr2(i) Then
ArrResults(i) = "Matches"
countMatches = countMatches + 1
Else
ArrResults(i) = "No Match"
End If
Next i
'Print out the results array in debug window
For Each entry In ArrResults
Debug.Print entry
Next entry
Dim ratio As Double
ratio = countMatches / (UBound(Arr1) + 1)
MsgBox (ratio * 100 & "%")
End Sub
Message box will display this:
Immediate window will display the results array values like this:
Try this:
Sub Test()
Dim str1 As String, str2 As String
Dim arr, i As Long, cnt As Long
str1 = "726741,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X"
str2 = "726742,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X"
For i = LBound(Split(str1, ",")) To UBound(Split(str1, ","))
If Not IsArray(arr) Then
arr = Array(IIf(Split(str1, ",")(i) = _
Split(str2, ",")(i), "Match", "NoMatch"))
Else
ReDim Preserve arr(UBound(arr) + 1)
arr(UBound(arr)) = IIf(Split(str1, ",")(i) = _
Split(str2, ",")(i), "Match", "NoMatch")
End If
Next
'~~> Check the array
For i = LBound(arr) To UBound(arr)
Debug.Print arr(i)
If arr(i) = "Match" Then cnt = cnt + 1
Next
'~~> output the percentage
MsgBox Format(cnt / (UBound(arr) + 1), "0.00%")
End Sub