Passing arguments in a loop

tiredofit

Well-known Member
Joined
Apr 11, 2013
Messages
1,148
Instead of writing this:

Rich (BB code):
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]Option Explicit[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]
Sub Calling()[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]
    Call Module1.Called(somearg:=1)
    
    Call Module1.Called(somearg:=2)
        
    Call Module1.Called(somearg:=3)
        
End Sub[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]
Sub Called(ByRef somearg As Integer)[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]
    somearg = somearg + 1[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]
End Sub
I would like to use a loop, as follows:

Rich (BB code):
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif][FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]Option Explicit

[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]Sub Calling()
    
    Dim ArgArray() As Variant
    
    ArgArray() = Array(1, 2, 3)
    
    Dim i As Integer
    
    For i = LBound(ArgArray(), 1) To UBound(ArgArray(), 1)

[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]        Call Module1.Called(somearg:=CInt(ArgArray(i)))

[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]    Next I

[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]End Sub[/FONT]
[/FONT][FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]
It works but how can I adapt it if Called takes more than one argument?

For example, if Called looked like this:

Rich (BB code):
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]Sub Called(ByRef somearg As Integer, ByRef somearg2 As Integer)[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]
    somearg = somearg2 + 1[/FONT]
[FONT=Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif]
End Sub
how do I change ArgArray in Calling so it passes the args "in pairs"?

Thanks


[/FONT]
<strike></strike>
[/FONT]
<strike></strike><strike></strike>
[/FONT]
<strike></strike>
 

Some videos you may like

Excel Facts

Can you AutoAverage in Excel?
There is a drop-down next to the AutoSum symbol. Open the drop-down to choose AVERAGE, COUNT, MAX, or MIN

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
38,785
Office Version
365
Platform
Windows
How about
Code:
Sub tiredofit()
    Dim Ary As Variant
    Dim i As Long
    
    Ary = Array(1, 2, 3, 4, 5, 6)
    For i = 0 To UBound(Ary) Step 2
        Call test(CLng(Ary(i)), CLng(Ary(i + 1)))
    Next i
End Sub
Sub test(arg1 As Long, arg2 As Long)
    arg1 = arg1 * arg2
    Debug.Print arg1
End Sub
 

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
38,785
Office Version
365
Platform
Windows
You're welcome & thanks for the feedback
 

Watch MrExcel Video

Forum statistics

Threads
1,095,781
Messages
5,446,462
Members
405,403
Latest member
horace james

This Week's Hot Topics

Top