4

VBA は名前空間 (Java ユーザー向けのパッケージ) をサポートしていません。他の言語の名前空間は、あいまいさを回避し、メンバー名のオートコンプリートなどのツールを補完するのに役立ちます。

VBA で名前空間をシミュレートする 1 つの方法は、クラス モジュールで事実上の静的メソッドを宣言し、標準モジュールでそのクラスの既定のインスタンスを宣言することです。これは、いくつかの Microsoft のドキュメントでも採用されているパターンです。このアプローチを使用して、疑似名前空間をネストすることもできます。

同業者の皆さん、このアプローチを使用することで技術的な問題が発生することは予想されますか?

これは世論調査の質問ではありません。正統性や美的魅力について尋ねているわけではありません。「これは問題を引き起こしますか? もしそうなら、何をしますか?」と私は尋ねています。

例:

' Class module called clsIOText
Public Function ReadAllText(ByVal FileName As String) As String
    With New FileSystemObject
        With .OpenTextFile(FileName, ForReading)
            ReadAllText = .ReadAll
            .Close
        End With
    End With
End Function

' Class module call clsIO
Public Text As New clsIOText

' In a standard module somewhere
Public IO As New clsIO

' Usage like a namespace
' 1. Fully qualified
Debug.Print IO.Text.ReadAllText("C:\temp\example.txt")

' 2. With a namespace alias-like object
Dim Text As clsIOText
Text = IO.Text
Debug.Print Text.ReadAllText("C:\temp\example.txt")
4

1 に答える 1

3

No other answers so far...

The pitfalls I've come up with myself are more limitations and gotchas:

  1. You need to set the Instancing property of each class to "2 - PublicNotCreatable". Otherwise if the project is compiled and then referenced from another project, the members will not appear in the Object Browser (though they will still be useable)
  2. You cannot declare external API declarations in a class module as Public. In order to expose them to code outside the class you must do the Declare as private and then make a public wrapper method.
  3. This still does not allow you to organize types in namespaces -- only collections of static methods.
  4. From queries and macros you can only call global methods defined in a standard module. So to use any functions wrapped up in namespace classes you'll have to define wrappers in a standard module, reflattening the heirarchy.
于 2013-02-19T20:49:20.240 に答える