# Difference between revisions of "ZH/Documentation/BASIC Guide/Procedures and Functions"

Jump to: navigation, search

 doc OOo

## 过程

```Sub Test
' ... here is the actual code of the procedure
End Sub```

## 函数

```Function Test
' ... here is the actual code of the function
Test = 123
End Function```

```Dim A
A = Test```

```Function Test
Test = 12
' ...
Test = 123
End Function```

```Function Test As Integer
' ... here is the actual code of the function
End Function```

## 提前终止过程和函数

```Sub Test
Dim ErrorOccured As Boolean
' ...
If ErrorOccured Then
Exit Sub
End If
' ...
End Sub```

## 传递参数

```Sub Test (A As Integer, B As String)
' ...
End Sub```

```Sub Test
Dim A As Integer
A = 10
ChangeValue(A)
' The parameter A now has the value 20
End Sub

Sub ChangeValue(TheValue As Integer)
TheValue = 20
End Sub```

```Sub ChangeValue(ByVal TheValue As Integer)
TheValue = 20
End Sub```

## 可选参数

Apache OpenOffice Basic 允许将参数定义为可选参数，也就是说，如果调用中不包含相应的值，Apache OpenOffice Basic 将传递一个空参数。在以下示例中，A 参数是必需的，而 B 参数是可选的。

```Sub Test(A As Integer, Optional B As Integer)
' ...
End Sub```

IsMissing 函数用于检查是传递还是省略了某个参数。

```Sub Test(A As Integer, Optional B As Integer)
Dim B_Local As Integer
' Check whether B parameter is actually present
If Not IsMissing (B) Then
B_Local = B      ' B parameter present
Else
B_Local = 0      ' B parameter missing -> default value 0
End If
' ... Start the actual function
End Sub```

## 递归

```Sub Main
Msgbox CalculateFactorial(  42 )    ' Displays 1,40500611775288E+51
Msgbox CalculateFactorial( -42 )    ' Displays "Invalid number for factorial!"
Msgbox CalculateFactorial( 3.14 )   ' Displays "Invalid number for factorial!"
End Sub

Function CalculateFactorial( Number )
If Number < 0 Or Number <> Int( Number ) Then
CalculateFactorial = "Invalid number for factorial!"
ElseIf Number = 0 Then
CalculateFactorial = 1
Else
' This is the recursive call:
CalculateFactorial = Number * CalculateFactorial( Number - 1 )
Endif
End Function```

 Content on this page is licensed under the Public Documentation License (PDL).