How do you count the list of strings VBA Excel? - vb.net

I'm still new to VBA Excel coding. Do tell me if there's anything that needs improvement.
In the example below I'm trying to get the list of even values from the generate class and insert into the excel vba sheet. But how do I count the number of list returned?
Private Function Generate()
Dim red(1 To 20) As String
For i = 1 To 20
red(i) = i * 2
Next i
Generate = red()
End Function
Sub Format()
Dim str() As String
str() = Generate
Range("A1").Select
With Selection
For i = 1 To str().Count 'what do I do with this? Obviously str().Count is not working.
.Offset(1, i).Value = str(i)
Next
End With
End Sub
Thank you.

Managed to solve on my own and here is the answer:
Private Function Generate()
Dim red(1 To 20) As String
For i = 1 To 20
red(i) = i * 2
Next i
Generate = red()
End Function
Sub Format()
Dim str() As String
str() = Generate
Range("A1").Select
With Selection
For i = LBound(str) To UBound(str)
.Offset(i - 1, 0).Value = str(i)
Next
End With
End Sub

Related

Can a VBA custom function knows that the formula is entered as an array formula?

Is it possible to make the following function returns either multiple values or single value according to how the user enters formula?
Public Function Test(ByVal flNumber As Double) As Variant
Dim flResult1 As Double
Dim sResult2 As String
Dim bArrayFormula As Boolean
flResult1 = Round(flNumber / 10 ^ 6, 1)
sResult2 = "million"
' How to know that the formula is entered as an array formula?
If bArrayFormula Then
Test = Array(flResult1, sResult2)
Else
Test = flResult1 & " " & sResult2
End If
End Function
Just examine Application.Caller
Public Function SmartFunction() As String
addy = Application.Caller.Address
If Range(addy).HasArray Then
SmartFunction = "Array Formula"
Else
SmartFunction = "Normal Formula"
End If
End Function

Why ListBox doesn't have a FindString method in Excel-VBA?

Trying to search on a ListBox. Specifically, I want to look at an array of items from the Cell, and for each one that matches an entry in the ListBox, I want it to select that List.
I copy-pasted some code that was supposed to let me find a string, but it keeps telling me:
Compile Error: Method or Data Member not found.
Any suggestions?
Relevant Code:
Public local_Target As Range
' local_Target is assigned in the sheet function to pass it here
Private Sub Network_ListBox_Enter()
' Get data in cell (if any)
Dim current_data As String
Dim entries() As String
current_data = local_Target.Value
If current_data = "" Then
Exit Sub
Else
entries = Split(current_data, vbNewLine)
End If
For Each Item In entries
FindMyString Item
Next Item
End Sub
Private Sub UserForm_Terminate()
Dim index As Integer
Dim result As String
' Iterate through the listbox and create the result, then assign to
' Target.value
For index = 0 To Network_ListBox.ListCount - 1
If Network_ListBox.Selected(index) Then
' stuff
If result = "" Then
result = Network_ListBox.List(index)
' ElseIf index = Network_ListBox.ListCount - 1 Then
' result = result + Network_ListBox.List(index)
Else
result = result + vbNewLine + Network_ListBox.List(index)
End If
End If
Next index
local_Target.Value = result
End Sub
Sub FindMyString(ByVal searchString As String)
' Ensure we have a proper string to search for.
If searchString <> "" Then
' Find the item in the list and store the index to the item.
Dim index As Integer
index = Me.Network_ListBox.FindString(searchString)
' Determine if a valid index is returned. Select the item if it is valid.
If index <> -1 Then
Network_ListBox.SetSelected index, True
'Else
' MessageBox.Show ("The search string did not match any items in the ListBox")
End If
End If
End Sub
I checked Intellisense and I don't think that Method is supported in VBA. Other documentations I've found refers to .Net Framework only as well. So maybe, it is not really supported in VBA, but regardless, you can create a function to do just that. Something like below.
Private Function SearchString(mysearch As String, mylist As Variant) As Long
Dim itm As Variant, idx As Long: idx = 0
If IsArray(mylist) Then
For Each itm In mylist
If mysearch = itm Then
SearchString = idx: Exit Function
End If
idx = idx + 1
Next
End If
SearchString = -1
End Function
And you can use it like this:
Private Sub CommandButton1_Click()
Dim i As Long
'do the search
i = SearchString("WhatImSearching", Me.ListBox1.List)
'select the item that match your search
If i <> -1 Then Me.ListBox1.Selected(i) = True
End Sub
I'm not saying that the function I created above is the most efficient way.
That is just an example to give you an idea for a workaround. HTH.
Important: This works in single column ListBox which have a 1D array list. If you need to work on multi-column ListBox, you'll have to tweak the function a little.

Sort Function (ascending) for Userform Listbox Excel

I am an IT enthusiast but I am not too good with programming or VBA. As a side project, I am compiling some data and would like to make it user friendly. I am new to forums so any advice would be welcome.
I have a Userform with a Listbox which has a large list of cities, but the list is unsorted. I understand i can go into the last page where I have the country capital list connected to the Listbox and sort the column there directly in the worksheet, but that would ruin my country list, so i would like to sort the list within the Userform Listbox, is there a way to do this?
I would also like to be able to add a Userform 'find' function within the Userform itself, as I have already done so, but I am unsure how to make it work despite trying some code, I failed, if you do know, then it would be great to hear whatever kind of advice, Thank you in advance.
Please find file in the link below with an image describing objectives and the code i currently have.
File:
https://www.sendspace.com/file/d4iaui
Sub Listb(target)
Location.ListBox1.List = Range("countrycapital").Value
For j = 0 To Location.ListBox1.ListCount - 1
Location.ListBox1.Selected(j) = False
Next j
currentrow = target.Row
'Location.Cells(19, 2) = Sheets("Practice List").Cells(target.Row, 3)
locval = target & ","
k = 0
For i = 1 To Len(locval)
Length = Abs(k - Application.WorksheetFunction.Search(",", locval, i))
Values = Mid(locval, i, Length - 1)
For j = 0 To Location.ListBox1.ListCount - 1
If Location.ListBox1.List(j) = Values Then
Location.ListBox1.Selected(j) = True
GoTo nxt
End If
Next j
nxt:
i = Application.WorksheetFunction.Search(",", locval, i)
k = i
Next i
Location.Show
End Sub
Sub newlocation()
Location.ListBox1.List = Range("countrycapital").Value
For j = 0 To Location.ListBox1.ListCount - 1
Location.ListBox1.Selected(j) = False
Next j
Location.Show
End Sub
Private Sub CommandButton1_Click()
Call ThisWorkbook.checkcriteria
End Sub
Private Sub CommandButton2_Click()
End Sub
Private Sub ListBox1_Click()
End Sub
Private Sub UserForm_Initialize()
Dim vaItems As Variant
Dim i As Long, j As Long
Dim vTemp As Variant
Me.ListBox1.AddItem "B" 'these new added values show on the userform
Me.ListBox1.AddItem "A" ' instead, I would like the original Listbox1...
Me.ListBox1.AddItem "D" ' ...incorporated within the sort function
Me.ListBox1.AddItem "C"
'Put the items in a variant array
vaItems = Me.ListBox1.List
'Steal code from John Walkenbach’s Excel Power Programming
'with VBA to sort the array
For i = LBound(vaItems, 1) To UBound(vaItems, 1) - 1
For j = i + 1 To UBound(vaItems, 1)
If vaItems(i, 0) > vaItems(j, 0) Then
vTemp = vaItems(i, 0)
vaItems(i, 0) = vaItems(j, 0)
vaItems(j, 0) = vTemp
End If
Next j
Next i
'Clear the listbox
Me.ListBox1.Clear
'Add the sorted array back to the listbox
For i = LBound(vaItems, 1) To UBound(vaItems, 1)
Me.ListBox1.AddItem vaItems(i, 0)
Next i
End Sub
Private Sub ListBox1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
HookListBoxScroll Location, Location.ListBox1
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
UnhookListBoxScroll
End Sub
My 2 cents :
- in order to sort things, I usually use the .Net Sort function. Some are accessible via Com Wrapper : CreateObject("System.Collections.ArrayList")
- this object has a .Contains function, that could be use by your Find function.
Hope this helps !

Spliting a string in VBA to get a list of numeric values

I would like to split the following string "2/3/4/4" for example and get each number and save them as a list.
I can split the string with the code split("2/3/4/4", "/") but then I cannot manage to put them in a list.
Any help is appreciated.
Yes, like engineersmnky says you can just return the results of Split() to a String array, like this:
Public Sub Test()
Dim results() As String
Dim i As Integer
results = Split("2/3/4/4", "/")
For i = LBound(results) To UBound(results)
MsgBox results(i)
Next i
End Sub
This would split "2/3/4/4" and put the numbers in A1:A4
Sub SplitAndList()
Dim nums As Variant, n As Integer
nums = Split("2/3/4/4", "/")
For n = 0 To UBound(nums)
Range("A" & n + 1) = nums(n)
Next n
End Sub

FILTER Function for integers - VBA

I searched the website but was not succesfful and tried doing some research on this but facing with " Type Mismatch" error.
I declared an array as integer type but the FILTER function seems to work only with STRING's. Can you please let me know how I can use the FILTER function for integers?
If UBound(Filter(CntArr(), count)) > 0 Then
msgbox "found"
End If
as i understand you need to know if specified count present in array. You can use for loop for it:
Dim found as Boolean
found = False
For i = 0 To UBound (CntArr())
If CntArr(i) = count Then
found = True
Exit For
End If
Next i
If found Then msgbox "found" End If
Below I have created IsIntegerInArray() function that returns boolean. Follow the two Subs for an example of integer array declaration. Declaring array as Integer should also prevent some unnecessary bugs caused by implicit data conversion.
Sub test_int_array()
Dim a() As Integer
ReDim a(3)
a(0) = 2
a(1) = 15
a(2) = 16
a(3) = 8
''' expected result: 1 row for each integer in the array
Call test_printing_array(a)
End Sub
Sub test_printing_array(arr() As Integer)
Dim i As Integer
For i = 1 To 20
If IsIntegerInArray(i, arr) Then
Debug.Print i & " is in array."
End If
Next i
End Sub
Function IsIntegerInArray(integerToBeFound As Integer, arr() As Integer) As Boolean
Dim i As Integer
''' incorrect approach:
''' IsIntegerInArray = (UBound(Filter(arr, integerToBeFound)) > -1) ' this approach searches for string, e.g. it matches "1" in "12"
''' correct approach:
IsIntegerInArray = False
For i = LBound(arr) To UBound(arr)
If arr(i) = integerToBeFound Then
IsIntegerInArray = True
Exit Function
End If
Next i
End Function