VBA - 如何调用代码段?

时间:2014-02-21 12:55:36

标签: excel excel-vba vba

我对Excel中的VBA世界还很陌生,所以这可能是一个非常明显的问题。

我有两段代码,在我编写的长脚本中经常使用。我想要做的是理想地给这两段代码命名,然后在需要时“调用”它们,而不是每次都写出来(每行大约30行代码)。

这可能吗?如果可行,我该怎么做?

2 个答案:

答案 0 :(得分:3)

例如,如果满足条件,则有2个变量可供添加;

Sub Main()

    Dim x As Double
    Dim y As Double
    Dim sum As Double

    x = 2
    y = 3
    If x > y And x > 0 And y > 0 Then
        sum = x + y
    End If

    x = 7
    y = 8
    If x > y And x > 0 And y > 0 Then
        sum = x + y
    End If

End Sub

DRY principle之后,您可能想要创建一个函数。一个函数将获取2个参数并在满足条件时返回总和,因此您可以反复使用它而无需在整个地方重复if statement

例如

Function AddIfConditionMet(x As Double, y As Double)
    If x > y And x > 0 And y > 0 Then
        AddIfConditionMet = x + y
    Else
        AddIfConditionMet = -1
    End If
End Function

每次调用此函数时,它都会检查条件 - 如果满足条件,则会添加xy否则会返回-1

示例代码

Sub Main()

    Dim x As Double
    Dim y As Double
    Dim sum As Double

    x = 2
    y = 3
    sum = AddIfConditionMet(x, y) ' returns -1
    Debug.Print sum

    x = 10
    y = 5
    sum = AddIfConditionMet(x, y) ' returns 15
    Debug.Print sum

End Sub

Function AddIfConditionMet(x As Double, y As Double)
    If x > y And x > 0 And y > 0 Then
        AddIfConditionMet = x + y
    Else
        AddIfConditionMet = -1
    End If
End Function

答案 1 :(得分:0)

sub main
 dim a as long
 call First_Macro ( arg1, Arg2 , Arg3)      'same as : First_macro arg1, Arg2, Arg3
 a= Some_Function_Name ( Arg1, Arg2, Arg3)
End sub



Sub First_macro (Byval arg 1 as string, byval arg2 as long, byref arg3 as range)
 'do something
end sub


Function Some_Function_Name ( Arg1, Arg2, Arg3) as long 'returns a Long type value
 'Do something
 if sometthing happens then
     Some_Function_Name=x
 else
     Some_Function_Name=x+1 'for example
 end if
end function