passing an argument to a sub

lezawang

Well-known Member
Joined
Mar 27, 2016
Messages
1,805
Office Version
  1. 2016
Platform
  1. Windows
Hi
I need you help understanding how to pass an argument to a sub. In this article the author said

"VBA procedures can be passed data via arguments, which are declared in the procedure definition. For example, you could have a VBA Sub procedure that adds an Integer to every cell in the current selected range on a worksheet. You could supply the value of the integer to the Sub via an argument, as follows:"

my question, how can I pass an argument to a sub. I mean lets talk about the example above. I highlight these cells that I want to add an integer to. I insert a control button and assign it to that Macro. Now I click the button to run the macro. How and when I can pass the argument?

Thank you very much.

source: VBA Function and Sub Procedures
 

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
Not really a good example, you can't directly pass values to code via a button.

If you did want to do something with the selected cells though you could do something like this.
VBA Code:
Sub Button1_Click()
    Call ProcessRange(Selection)
End Sub

Sub ProcessRange(ByVal rng As Range)
    MsgBox "These are the selected cells: " & rng.Address
End Sub
 
Upvote 0
The procedure can be called only by writing the name and argument:

VBA Code:
Private Sub CommandButton1_Click()
  Process_selected_cells 5
End Sub

Or with Call statement

VBA Code:
Private Sub CommandButton1_Click()
  Call Process_selected_cells(5)
End Sub


This could be an example for the procedure

VBA Code:
Sub Process_selected_cells(i As Integer)
  Dim c As Range
  For Each c In Selection
    c = c + i
  Next
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,063
Messages
6,122,930
Members
449,094
Latest member
teemeren

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top