leon Hill
leon Hill

Reputation: 93

how to call a function within an if statement (vba)

I am trying to call a function within my if statement. The function is called classyear and is just after the if. I am trying to run through a timetable and see what classes belong to each year. so if it ends in a 1 it will be counted. Does anyone know how I would go about calling the function? Any help is appreciated

Public Sub time() 
Dim rgTimeTable As Range, rgClass As Range, counter As Integer

Set rgTimeTable = Range("B3, N11")

For Each rgClass In rgTimeTable
If rgClass.Value = classyear Then counter = counter + 1     ' classyear is the function 

Next rgClass
MsgBox test     ' also a function 

End Sub

EDIT Code for the function i am trying to call

Public Function classyear(class As String) As Integer

Dim yr As String

yr = Right(class, 1)
If IsNumeric(yr) Then classyear = yr Else classyear = 0

End Function

Upvotes: 1

Views: 8410

Answers (2)

CallumDA
CallumDA

Reputation: 12113

Your classyear function takes a string input, so you need to give it one. Something like:

If CInt(rgClass.Value) = classyear("Year1") Then counter = counter + 1 

Also you can neaten up your classyear function:

Public Function classyear(class As String) As Integer
    On Error Resume Next 'if error classyear will return 0
    classyear = CInt(Right(class, 1))
End Function

Upvotes: 1

Ambrish Pathak
Ambrish Pathak

Reputation: 3968

You can call a Sub inside if block like:

(Use function if you want to return some value else use Sub)

if (...)

   classyear() '<--Calling the Sub defined below

End if 



Private Sub classyear()
  .
  .
End Sub

Hope this is what you are looking for.

Upvotes: 0

Related Questions