2011-06-07 179 views
9

我在VBA中有簡單的功能,我需要檢查它是否已經成功執行。我不太瞭解VBA,所以我不知道它是否可行。我想要做這樣的事情:bool X=MyFunction()函數返回布爾值?

我在QTP描述性編程中使用VBA。這不起作用:

Function A as Boolean 
    A=true 
End Function 

它說:Expected statement

,但我看不到任何返回類型在我的方法等

回答

18
function MyFunction() as Boolean 
    ..... 
    ..... 
    MyFunction = True 'worked 
end function 

dim a as boolean = MyFunction() 
6

在VBA中,您可以通過分配設置函數的返回值的變量具有相同名稱的功能:

Function MyFunc() as Boolean 
    MyFunc = True 
End Function 
+0

謝謝,我沒有寫它的VBA QTP內。當我嘗試這個時,它說「期望的聲明」。 – Mirial 2011-06-07 12:22:22

+0

這是什麼QTP? – codeape 2011-06-07 12:25:03

+0

惠普Quick Test Professional。 – Mirial 2011-06-07 12:26:37

0

那麼如果你有機會ŧ o你的函數聲明,你可以爲它設置一個bool返回類型,並根據執行返回true或false。 一旦你的函數返回一個布爾值,你的代碼就可以工作。

0

沒有真正的方法來檢查函數是否在VBA中工作。你必須自己決定你的功能是否成功。例如:

Function AFunction() as Boolean 
    on error goto 1 
    MyFunc = True 
    AFunction = True 
    Exit Function 
    1 
    AFunction = False 
End Function 

上面的代碼會讓你知道函數是否失敗。如果失敗,則轉到標籤「1」,然後返回false,否則返回true。

如果它不是您正在查找的「錯誤」,那麼您必須確定返回或提供的數據是否正確。這樣做的一種方法是返回一個代表失敗的特定值[error-code]。

3

我懷疑你可能使用VBScript而不是VBA?如果是這樣的話,那麼VBScript不狀態類型

這將在VBScript

dim test,b 
test = 1 
b=false 
msgbox ("Calling proc before function test=" & test) 
msgbox("Calling proc before function b=" & b) 
b = A(test) 
msgbox ("Calling proc after function test=" & test) 
msgbox("Calling proc after function b=" & b) 

Function A(test) 
test = test +1 
A=true 
End Function 

或工作在你的榜樣

Function A()  
A=true 
End Function