• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

How to write and call functions from a module

ThrottleWorks

Excel Ninja
Hi,

I hardly use functions in my coding. However I want to learn how to write functions and call from module.

Can anyone please share links which will help me understanding functions. Thanks.
Please see below example for your reference.


Code:
Sub File_Select()
Call FilePicker(Sheet1.TextBox1)
End Sub

Sub FilePicker(ByRef txt As Object)

  With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False

  .Show

  If .SelectedItems.Count > 0 Then txt.Value = .SelectedItems(1)

  End With

End Sub
 
Last edited by a moderator:
Here is a basic example

Code:
Sub List1()

Dim i As Integer
Dim j As Integer

'Make a  table of i & i^2
For i = 1 To 10
  j = square(i)
  Debug.Print i; j

Next i
End Sub

Code:
Sub List2()

Dim i As Integer
Dim j As Integer

'Make a  table of i & i^2+10
For i = 1 To 10
  j = square(i) + 10
  Debug.Print i; j

Next i
End Sub

Code:
Function square(myNumb As Integer) As Integer
  square = myNumb * myNumb
End Function

You can see that the first module List1 makes a list of integers between 1 and 10 and the square of each number

It uses a function Square() to work out the square

Because square is a generic sort of function that you are likely to use in other applications, it can be used as in List1, where the numbers and the squares+10 are printed
 
For a sample where multiple values are sent to the function

Code:
Sub List3()

Dim i As Integer
Dim j As Integer

'Make a  table of i * j
For i = 1 To 10
for j = 1 to 10
  k = product(i,j)
  Debug.Print i; k

Next i
End Sub

Code:
Code (vb):
Function Product(myNumb1 As Integer, myNumb2 As Integer) As Integer
  Product = myNumb1 * myNumb2
End Function
 
Hi @Hui sir and @Marc L sir, thanks a lot for the help.

Am going through this and will revert with details.

Have a nice day ahead. :)

PS - Was trying to post yesterday only. Somehow it was not done. Just was as auto-complete while referring post.
 
Back
Top