2017-02-16 156 views
3

在VBA中,是否有任何已知的機制來欺騙編譯器,允許使用保留關鍵字作爲類屬性的名稱?例如,我想在我的一個課程模塊中創建一個名爲Select的屬性。但是,編譯器將我的聲明標記爲錯誤。下面是我使用的語法:VBA - 具有保留關鍵字的類屬性

Public Property Get Select() As Database.SQLStatements 

End Property 

Database是我的VBA項目名稱和SQLStatements是我創建的類模塊之一。另外,我正在MS Access 2010中運行代碼。

+0

您需要的搜索是「vba使用保留字作爲標識符」,它提供了[Access 2007保留字和符號](https://support.office.com/zh-cn/article/Access-2007-reserved-words -and-symbols-e33eb3a9-8baa-4335-9f57-da237c63eabe),其表示用方括號包圍標識符。 –

回答

7

您可以這樣做並在您的VBA中使用任何關鍵字/保留字。但是,它會使你的代碼變得非常混亂,而且很難讀取/調試/維護。

如果你的課堂中有一個名爲If的布爾屬性,你最終會得到類似If .If  Then的東西,那麼,祝你好運。另外代碼維護如查找/替換/重命名等將需要額外的謹慎和更多的工作。


無論如何,如果你願意經歷所有這些痛苦,這裏是你如何做到這一點。 關鍵字/保留字使用ALT + 0160添加了一個不可見的空白空間後,就是這樣。 VBA會認爲它是一個完全合法的名稱。例如If 

另外,您將不得不使用智能感知來使用這些屬性名稱,或者手動輸入任何地方的altcode。這是額外的打字。


另clsTest

Option Explicit 

Private m_sSelect As String 
Private m_bIF  As Boolean 

Public Property Get Select () As String '~~> Select () is actually typed as SelectALT+0160() 
    Select  = m_sSelect 
End Property 

Public Property Let Select (ByVal sNewValue As String) 
    m_sSelect = sNewValue 
End Property 

Public Property Get If () As Boolean 
    If  = m_bIF 
End Property 

Public Property Let If (ByVal bNewValue As Boolean) 
    m_bIF = bNewValue 
End Property 

測試模塊

Option Explicit 

Sub demo() 

    Dim objTestClass As clsTest 

    Set objTestClass = New clsTest 

    With objTestClass 
     .Select  = "It works. But it will, for sure, create readibility/maintenance issues." 
     .If  = False 
    End With 

    MsgBox objTestClass.Select  

    '/ See how hard it will to read/debug this sort of code 

    With objTestClass 
     If .If  Then '~~> This line here :) 
      MsgBox "If prop value is TRUE" 
     Else 
      MsgBox "If prop value is FALSE" 
     End If 
    End With 

End Sub 

ALT + 0160 <>空間

+1

謝謝你給我一個很好的解決方法。我並不太熱衷於額外的空間,但它絕對有用,並且我學到了新的東西。 –

+1

++一如既往的盒子思維。 – teddy2

+1

我永遠不會使用它,但很高興知道ALT + 0160 –