我對Excel中的VBA世界還很陌生,所以這可能是一個非常明顯的問題。VBA - 如何調用一段代碼?
我有2段代碼,我經常在整個我寫的長腳本中使用。我想要做的是理想地給這兩段代碼一個名字,然後在需要時「調用」它們,而不是每次都寫出它們(每行約30行代碼)。
這是可能的,如果是這樣,我該怎麼做?
我對Excel中的VBA世界還很陌生,所以這可能是一個非常明顯的問題。VBA - 如何調用一段代碼?
我有2段代碼,我經常在整個我寫的長腳本中使用。我想要做的是理想地給這兩段代碼一個名字,然後在需要時「調用」它們,而不是每次都寫出它們(每行約30行代碼)。
這是可能的,如果是這樣,我該怎麼做?
例如,如果您有兩個變量,如果條件滿足,您繼續添加;
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
每次調用這個函數時它會檢查的條件 - 如果他們滿足,那麼它增加了x
和y
如果沒有則返回-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
這是一個很好的答案,非常詳細。但是,我不確定它是否太深入我所需要的。你的例子似乎需要條件。當我詢問它時,我只想調用一個'函數'。這可能是多次在同一個腳本,但做了不同的事情後.....如果這是有道理的。 – Petay87
您可以將您的功能轉換爲程序。這很容易,但請記住,過程不會返回值。看到亞歷克斯的評論下你的問題:) – 2014-02-22 23:51:15
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
您的評論是誤導。請參閱使用帶和不帶括號的參數調用subs /函數。它們是將對象傳遞給函數的不同方式(byRef和ByVal) – 2014-02-22 23:52:17
代碼行在nam中組合在一起編輯子程序或函數。 要執行它們,只需簡單地址(呼叫)該名稱即可。請參閱*創建和調用過程* @ http://msdn.microsoft.com/en-us/library/office/aa188202(v=office.10).aspx –
另請參閱此http://www.anthony-vba。 kefra.com/vba/vbabasic1.htm#Calling_Sub_Procedures_and_Function –