Call multiple macro using array and function in excel vba - vba

I am unable to call macros whose names I have stored in a String Array.
I attach the code.
Option Explicit
Option Compare Text
Dim i, Ro As Integer
Public Sub Universal_Macro()
Dim Col(10) As Integer
Dim macro_name(10) As String
Ro = ActiveCell.Row
i = 1
For i = 1 To 10
Call Mac_Sched(Col(), macro_name())
Next
End Sub
Sub Mac_Sched(Col() As Integer, Internal_Array() As String)
Cells(Ro, Col(i)).Select
Call Internal_Array(i)
End Sub
Getting error in the sub Mac_Sched.

Try to use Application.Run:
Sub RunMc()
Dim a(1 To 2) As String
Dim MN As String
For i = 1 To 2 'Fill the array
a(i) = "m" & i
Next
MN = "Module1" 'the module name
For i = LBound(a) To UBound(a)
Application.Run MN & "." & a(i)
Next
End Sub
Sub m1()
Debug.Print "m1"
End Sub
Sub m2()
Debug.Print "m2"
End Sub

TBBH, I really don't know what you are trying to accomplish and the heavily redacted code does nothing to show specific methods other than the attempt at calling a macro from a string derived from an array element.
The Application.OnTime method uses a string as the name of the procedure to call.
Option Explicit
Option Compare Text
Dim i As Integer, Ro As Integer
Sub zero()
Debug.Print "zero: " & i
End Sub
Sub first()
Debug.Print "first: " & i
End Sub
Sub second()
Debug.Print "second: " & i
End Sub
Sub third()
Debug.Print "third: " & i
End Sub
Public Sub Universal_Macro()
Dim Col() As Integer
Dim macro_Name As Variant
macro_Name = Array("zero", "first", "second", "third")
ReDim Col(UBound(macro_Name))
For i = LBound(macro_Name) To UBound(macro_Name)
Col(i) = i
Next
Ro = ActiveCell.Row
For i = LBound(macro_Name) To UBound(macro_Name)
Call macro_Sched(Col(i), macro_Name)
Next
End Sub
Sub macro_Sched(c As Integer, internal_Array As Variant)
Cells(Ro, c + 1).Select '<~~Don't rely on Select! You dont' even reference a worksheet here.
Application.OnTime Now, internal_Array(c)
End Sub
If parameters were to be passed to the children sub procedures, then some sort of string replacement might accommodate this but specifics on the child subs are not evident.
See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals.

Related

Print array in textbox

Im doing code where button 1 will get data from worksheet and store in array, and button 2 will print the array in worksheet and textbox.
Public arr As Variant
Private Sub UserForm_Click()
End Sub
Private Sub CommandButton1_Click()
arr = Range("B8:C17")
Range("B8:C17") = Clear
End Sub
Private Sub CommandButton2_Click()
Range("B8:C17") = arr
TextBox1.Text = arr
End Sub
Private Sub CommandButton3_Click()
Unload Me
End Sub
Everthing is fine excepet it does not print array in textbox. what is wrong here ?
So what you need to do is loop through your rows of array data and populate it one by one.
Firstly, you need to make sure to set Multiline to True in your textbox properties.
Then add this:
Private Sub CommandButton2_Click()
Range("B8:C17") = arr
Dim i As Long
For i = 1 To UBound(arr, 1)
Me.TextBox1.Text = Me.TextBox1.Text & arr(i, 1) & Chr(9) & arr(i, 2) & vbCr
Next i
End Sub
Note:
This will only work for 2 columns in the array. If you have more, you will need to add another & arr(i, x) to the line with x being the column number.
If you need an extra tab between the 2 columns, add another & Chr(9) to the line next to the already existing one.
See if that works for you.

How change the name of an object with a for loop vba?

I would like to import multiple pictures with a for loop using a table in vba, but I have a problem with the named object. I don't konw how to deal with it (lake of experience):
Public Table_glob(1) As Variant
Sub Table_glob()
table(0) = "toto"
table(1) = "tata"
End Sub
Sub Insert()
Call Table_glob
For i = LBound(table) To UBound(table)
Set shp_ & table(i) & = ActivePage.Import("C:\Users\antho\Documents\" & table(i) &".png")
Next i
End Sub
I have an error message : "expected: =" on the first "&"
Sub Insert()
Dim table(0 To 1) As Variant
Dim shp_table(0 To 1) As Variant
table(0) = "toto"
table(1) = "tata"
For i = LBound(table) To UBound(table)
Set shp_table(i) = ActivePage.Import("C:\Users\antho\Documents\" & table(i) & ".png")
Next i
End Sub

Excel VBA Onaction with .Select or .ScrollColumn

Good Morning everyone,
I am facing a strange Problem in Excel VBA.
So, I have this minimal Example. The only thing it's supposed to do is, add a Button to the Rightklick context menu. This button should then select a cell.
I searched a bit on StackOverflow and found a solution to passing string arguments in .onaction. But then it gets tricky. I can assign a Range and I can Print the Address and the second Argument in a Mesgbox. But I can't set Breakpoints and even stop doesn't work, nor will .select or .ScrollColumn do anything.
To Replicate just copy the Following code into a standard Module and Execute AddContextmenu to add the Button to the Contextmenu.
Option Explicit
Public Sub AddContextmenu()
Dim MySubMenu As CommandBarControl
Dim i As Long
'Clear Previous Menu Items
For Each MySubMenu In Application.CommandBars("Cell").Controls
If Not MySubMenu.BuiltIn Then
MySubMenu.Delete
End If
Next
'add menu
AddScrollButtons Application.CommandBars("Cell"), 1
End Sub
Public Sub AddScrollButtons(ByVal ContextMenu As CommandBar, ByVal baseindex As Long)
Dim cbb As CommandBarButton
Dim sFunction As String
'Add Button
Set cbb = ContextMenu.Controls.Add(Temporary:=True)
With cbb
sFunction = BuildProcArgString("ScrolltoColTest", "$F$10", "TestArg") ' Get Onaction string
.OnAction = sFunction
.Caption = "Scroll Tester"
.Style = msoButtonAutomatic
End With
End Sub
Function BuildProcArgString(ByVal ProcName As String, ParamArray Args() As Variant)
Dim tempArg As Variant
Dim temp As String
For Each tempArg In Args
temp = temp + Chr(34) + tempArg + Chr(34) + ","
Next
BuildProcArgString = "'" & ThisWorkbook.Name & "'!" & ProcName + "(" + Left(temp, Len(temp) - 1) + ")" ' (Workbook has to be included to ensure that the sub will be executed in the correct workbook)
End Function
Public Sub ScrolltoColTest(Addr As String, OtherArg As String)
Dim cell As Range
Set cell = ActiveSheet.Range(Addr) 'Get Cell that sould be selected from Addr
MsgBox cell.Address & vbNewLine & OtherArg 'Test if the Arguments have been passed correctly and the cell has been assigned
Stop 'Why doesn' this stop?
cell.Select 'Why doesn't this do anything
ActiveWindow.ScrollColumn = cell.Column 'Why doesn't this do anything
End Sub
As you will see in ScrolltoColTest the Part after the Msgbox will not work at all.
Does anyone know why that happens?

(Excel VBA) How to Show AutoComplete Feature of a ComboBox as a DropDown List

I would like the following code to add values to a combobox, then when the user inputs characters into the combobox, the dropdown feature of the combobox will show only those items which contain those characters, similarly to the way the Google Search Bar works.
(source: intersites.com)
Code Edit:
Option Explicit
Option Compare Text
Public LC As Long
Public Count As Integer
Dim ComboArray() As String
'Initializes the userform, and saves values from database into an array
Private Sub UserForm_Initialize()
LC = Cells(1, Columns.Count).End(xlToLeft).Column
ReDim ComboArray(1 To LC)
For Count = 1 To LC
ComboArray(Count) = Cells(1, Count).Value
Next Count
End Sub
'Prevents changes if the down key is pressed?
Private Sub ComboBox_SiteName_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Application.ScreenUpdating = False
End Sub
'Adds values to combobox if they contain the string input by user
Private Sub ComboBox1_Change()
Dim pos As Integer
Dim i As Integer
ComboBox1.Clear
For Count = 1 To LC
pos = InStr(1, ComboArray(Count), ComboBox1.Value)
If pos <> 0 Then
With ComboBox1
.AddItem Cells(1, Count)
End With
End If
Next Count
End Sub
Here is a simple example, which may need refinement for your purposes, but illustrates the general principles of using the KeyPress event to build a string of user input, and compare that to each item in the list, effectively filtering the list to values that start with the input string.
This needs some refinement to handle backspacing, deleting, etc., which I tried to do, but didn't get as far as I'd like.
Code:
Option Explicit
Dim cbList As Variant
Dim userInput$
'### USERFORM EVENTS
Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 8, 48
'MsgBox "Backspace"
Debug.Print "Backspace"
If userInput <> "" Then
userInput = Left(userInput, Len(userInput) - 1)
End If
Case 46
'MsgBox "Delete"
Debug.Print "Delete"
userInput = Replace(userInput, ComboBox1.SelText, "")
End Select
End Sub
Private Sub UserForm_Activate()
Dim cl As Range
userInput = ""
For Each cl In Range("A1:A8")
Me.ComboBox1.AddItem cl.Value
Next
Me.ComboBox1.MatchRequired = False
cbList = Me.ComboBox1.List
End Sub
Private Sub UserForm_Terminate()
userInput = ""
End Sub
'#### END USERFORM EVENTS
'#### COMBOBOX EVENTS
Private Sub ComboBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Me.ComboBox1.List = cbList
' Capture the user input in module variable
userInput = userInput & Chr(KeyAscii)
Debug.Print "input: " & userInput
Debug.Print KeyAscii
Dim i As Long, itm
For i = Me.ComboBox1.ListCount - 1 To 0 Step -1
itm = Me.ComboBox1.List(i)
If Not StartsWith(CStr(itm), userInput) Then
Me.ComboBox1.RemoveItem i
End If
Next
If Me.ComboBox1.ListCount = 0 Then
Me.ComboBox1.List = cbList
Else
Me.ComboBox1.List = Me.ComboBox1.List
End If
Me.ComboBox1.DropDown
End Sub
'#### END COMBOBOX EVENTS
'#### HELPER FUNCTIONS
Function StartsWith(imtVal$, inputStr$, Optional caseSensitive As Boolean = False)
', Optional caseSensitive As Boolean = False
'If Not caseSensitive Then
imtVal = LCase(imtVal)
inputStr = LCase(inputStr)
'End If
StartsWith = VBA.Strings.Left(imtVal, Len(inputStr)) = inputStr
End Function
'#### END HELPER FUNCTIONS

How can i call a Sub using hyperlinks

I am newbie to VBA; I have a question:
How can I call sub to delete a cell in a sheet by using a Hyperlinks from another sheet.
A structure of the code is greatly appreciated.
Event handler in worksheet which contains the hyperlink:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
If Target.TextToDisplay = "Clear Cell" Then
ClearThatCell
End If
End Sub
Note there's also a Workbook-level event: use that if you'd like to be able to trap any hyperlink click in the workbook.
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, _
ByVal Target As Hyperlink)
End Sub
Called code:
Sub ClearThatCell()
ThisWorkbook.Sheets("Sheet2").Range("A1").ClearContents
End Sub
' Public m_data_wks As Worksheet
Sub init_links
Dim v_r As Range, n_rows as Integer
Set v_r = m_data_wks.Cells(1, 1)
n_rows = 3 'is an example of filling up cells with hyperlinks
For I = 1 To n_rows
v_r.Value = I
'The key: adding hyperlink to the v_r cell with a special subaddress for alternative usage.
'The hyperlink looks like the ordinary but points to itself.
m_data_wks.Hyperlinks.Add Anchor:=v_r, Address:="", SubAddress:=v_r.Address(External:=False, RowAbsolute:=False, columnAbsolute:=False)
Set v_r = v_r.Offset(1)
Next I
end sub
'Private WithEvents App As Application
Private Sub App_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Dim v_dst As Worksheet, v_index_s As String, v_index_i As Integer
'get_context sets v_dst the proper worksheet
'get_context Sh.Parent, v_dst
If v_dst Is Nothing Then Exit Sub
On Error GoTo Ext
'Using the value of the cell for choosing which to delete
v_index_s = CStr(Sh.Range(Target.SubAddress).Value)
If v_index_s = "#" Then
v_index_i = 0
Else
v_index_i = CLng(v_index_s)
End If
'Here the v_index_i points to the row instead of a cell for deleting
v_dst.Rows(v_index_i).Delete
Exit Sub
Ext:
If Err.Number <> 0 Then
MsgBox "Error occured while deleting by hyperlink: " & Err.Number & ", " & Err.Description, vbExclamation, "Non critical error"
Err.Clear
End If
End Sub