2013-02-12 66 views
1

我有其中值之一是由UDF返回的查詢:如何在查詢調用的UDF中使用靜態成員?

select name,coord,convertCoord(coord) from testTable; 

convertCoord()使用RegexMatchCollection對象返回其值:

Dim re As New RegExp 
Dim mtch As Match 
Dim matches As MatchCollection 

Function convertCoord(str As String) As String 

re.Pattern = "(find|this)pattern" 
Set matches = re.Execute(str) 
If matches.Count > 0 Then 
    Set mtch = matches(1) 
    convertCoord = mtch.Value 
Else 
    convertCoord = "" 
End If 

End Function 

我試圖加快查詢,我想知道是否有辦法讓remtchmatches的一個實例可以通過每次調用convertCoord()來引用。如果我理解正確,查詢中的每個結果行都會調用convertCoord(),這會重複構造和破壞所有對象,並且所有這些對象創建都會減慢查詢速度。

或者它們已經是靜態的,因此只構造一次,因爲我已經聲明它們不在函數中?

回答

1

當您聲明RegExp時,您可以使用Static關鍵字。但是,您只能在一個過程(函數或子例程)內使用它。如果您嘗試將其用於模塊級變量,則會觸發編譯器錯誤。

我不認爲你需要聲明MTCH的匹配,而Static,因爲你不希望從一個函數調用到下一個保留它們的值。我也不明白他們爲什麼應該是模塊級別的變量,所以我讓它們成爲本地函數。

Function convertCoord(str As String) As String 
Static re As RegExp 
Dim mtch As Match 
Dim matches As MatchCollection 

If re Is Nothing Then 
    Debug.Print "RegExp Is Nothing" 
    Set re = New RegExp 
    re.pattern = "(find|this)pattern" 
Else 
    Debug.Print "RegExp active" 
End If 

' insert code which uses the RegExp 

End Function 

測試與您的查詢類似的功能。確認後,打印「RegExp Is Nothing」不超過一次,您可能會想要放棄Debug.Print聲明。 :-)