如何在if语句中调用函数(vba)

时间:2017-04-03 09:22:10

标签: excel vba excel-vba excel-2016

我试图在if语句中调用一个函数。该函数称为classyear,位于if之后。我试图通过一个时间表,看看每年属于哪些类。所以,如果它以1结尾,它将被计算在内。有谁知道如何调用该函数?任何帮助表示赞赏

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 我试图打电话的功能代码

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

2 个答案:

答案 0 :(得分:1)

您的classyear函数接受字符串输入,因此您需要给它一个。类似的东西:

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

此外,您还可以阻止classyear功能:

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

答案 1 :(得分:0)

你可以在内部调用一个Sub,如:

(如果你想返回一些值,请使用函数,否则使用Sub)

if (...)

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

End if 



Private Sub classyear()
  .
  .
End Sub

希望这就是你要找的东西。

相关问题