vba项目引用和共享状态(用于记录)

时间:2014-01-31 15:33:48

标签: vba excel-vba excel

1 个答案:

答案 0 :(得分:0)

好的 - 所以这是我提出的解决方案(相当一些代码,但似乎工作正常):

我有一个日志记录项目,其日志记录界面ILog(Instancing PublicNotCreatable)就像    这样:

Public Sub Error(sLogMessage As String)
end sub
Public Sub Warning(sLogMessage As String)
end sub
' etc.

当然还有一个实现类CLog,它只是将消息写入日志文件 和一个公共函数,以便调用者可以获得记录器的新实例:

Public Function New_Log(ByVal logFilePathAndName) As ILog
    Set New_CLog = New CLog
    New_CLog.Initialise logFilePathAndName
End Function

然后项目C 必须在其初始化中获得ILog实例的类/类中包含所有代码。例如CSharedClass可能如此:

Private Log as ILog ' note: the var is intentionally NOT called moLog

Public Sub Initialise(oLogger as ILog)
    Set Log = oLogger
End Sub

' other functions in this class that want to log just use this:
Public Sub SomeProcedure()
    Log.Error("error text")
End Sub

此项目还必须有一个公共函数让调用者创建一个实例,如下所示:

Public Sub New_SharedClass(oLogger as ILog) as CSharedClass ' NOTE: you may want to use an interface instead
    Set New_SharedClass = New CSharedClass
    New_SharedClass.Initialise oLogger
End Sub

然后项目A和B 可以使用这样的日志记录:

Private moLog as ILog

Public Function Log() as ILog
    ' log-file name is of course different for Proejct B
    If moLog is Nothing then Set moLog = New_Log("ProjectA.log")
    Set Log = moLog
End Function

项目A / B中的所有其他程序现在可以像这样编写日志消息(与共享项目中的相同)

Log.Error("Error text")

当项目A / B想要使用共享项目时,它可以这样做

Private moSharedClass as CSharedClass 

Public Function SharedClass() as CSharedClass    
    If moSharedClass is Nothing then Set moSharedClass = New_SharedClass(Log)
    Set SharedClass = moSharedClass
End Function

现在项目A / B中想要在共享类上调用proc的任何代码都可以这样做:

SharedClass.SomeProcedure()

并且SomeProcedure中写入的日志消息将以正确的日志文件

结束

注意:我决定打破一些自己的命名规则,以便所有项目都可以使用相同的代码进行日志记录(这样做的好处是我可以将程序从项目A / B移动到共享项目,反之亦然)