在“ PROD”和“ DEV”模式之间快速切换

时间:2019-07-03 09:55:11

标签: excel vba debugging access-vba devops

我使用一些高级的自动宏开发VBA代码,这些宏在DEV阶段进行“连接”和额外的调试。 但是,当我将文件运送给用户时(PROD阶段),我希望所有这些功能都关闭。

在DEV和PROD之间进行的切换很多(git + devops方法)。

在DEV和PROD之间实现快速“切换”的最佳/最优雅的方法是什么? 是的,我可以只使用全局的Const isDebug(我在某些项目中也这样做过),但是它很繁琐,笨拙且容易出错(我不只一次忘记“翻转”开关了,就像我之前说的那样,敏捷而敏捷) “几乎” CI / CD管道)。

编辑

现在,我正在使用一个快速的肮脏的hack(我不喜欢肮脏的hack),它检查是否从路径中带有我的登录名的位置运行Excel文件。如果是,则表示我正在处理文件。如果没有,则其他人正在使用它,我们不需要任何调试模式。但这很丑陋,而且我可以预见到很多问题(例如,明天可能会有其他人在开发那些VBA ...因此调试代码必须重写)。

3 个答案:

答案 0 :(得分:1)

在VBE中转到其他-> VBAProject的属性,然后输入要编译的参数,例如:

DEV_MODE = -1

enter image description here
抱歉,德语屏幕截图。

然后使用以下代码

Option Explicit

Sub test()
    'the following #If is a compile condition
    #If DEV_MODE Then
        'this is only compiled in dev mode
        Debug.Print "debug mode is on"
    #Else
        'this is only compiled in production mode
        Debug.Print "debug mode is off"
    #End If
End Sub

请注意,在VBA中,-1True,而0False。切换编译参数DEV_MODE = -1将在整个VBA项目中切换开发模式。

答案 1 :(得分:1)

您可以在工作簿路径中使用文本文件作为条件。

如果文件丢失(例如“ DebugMode.txt”)或未设置调试选项(文本文件中的“ DebugMode:On”),请关闭调试模式,否则将其打开。

如果在不使用文本文件的情况下部署工作簿,则调试模式将关闭。

如果其他一些工具需要打开调试模式,请共享/创建文件。

示例代码:

Function IsDebugMode() As Boolean

Const DebugOptionFileName As String = "DebugMode.txt" 
Const DebugIsOnString As String = "DebugMode:On"
Const ForReading as Long = 1

Dim txtStream As Object
Dim DebugOptionFilePath As String

IsDebugMode = False
DebugOptionFilePath = ThisWorkbook.Path & "\" & DebugOptionFileName

With CreateObject("Scripting.Filesystemobject")
    If .FileExists(DebugOptionFilePath) Then
        Set txtStream = .OpenTextFile(DebugOptionFilePath, ForReading, False)
        Do Until txtStream.AtEndOfStream
            If txtStream.ReadLine = DebugIsOnString Then
                IsDebugMode = True
                Exit Do
            End If
        Loop
    End If
End With

End Function

答案 2 :(得分:0)

我不喜欢将开关设置为Compiler-Setting的尝试-忘记更改它比更改Const定义更有可能。

我发现您尝试检查用户名,设备名,文件路径或类似的东西不是太糟糕。只需将逻辑放入一个小的函数isTestMode()中(即使它是单行代码),该函数将返回一个boolean。在此功能内,如果其他人接管工作,则很容易变为逻辑。使用此功能(无其他功能!)检查是否执行调试语句。

Public Function isTestMode() as boolean
    ' Checking current user
    isTestMode = (environ("Username") = "FunThomas")
    ' Checking device name
    isTestMode = (environ("ComputerName") = "MySuperPC")
    ' Checking if a specific file is present
    isTestMode = Dir(thisworkbook.Path & "\IsTestMode") <> "")
End Function