I am trying to do the following in one module:
- Replace a
Public Constin another module, at run-time.
- Invoke a procedure that uses the updated public constant
However, it throws an error:
Can’t enter break mode at this time
Although, it does update the public constant.
I tried pressing F5 to resume execution, but it did not help. Any suggestions?
Sub AB() Call LoadQuoteDetails2.Automation Application.VBE _ .ActiveVBProject _ .VBComponents _ .Item("mod00Admin") _ .CodeModule _ .ReplaceLine 2, "Public Const QuoteDB = ""A:.0 Projects\P0445 Ireland Commercial Raters Analysis Rate Assessor\ROI Fleet Rater\Quote Database\Quote DB June 18.accdb""" Call CalcTariffPrem End Sub
As mentioned in the comments, you need to use global variable or property instead of a “constant”. The reason you’re getting the “Can’t Enter Break Mode at this time” message is because you are modifying the
VBProject that is currently running. Basically what is happening is that you are changing the source code while the already compiled code is still executing. A
Const is “hard coded” into the executing procedure, so changing it won’t do anything until the project is recompiled. In fact, the VBA language specification has no runtime semantics for Const Declarations (why would it?). For example…
Public Const EXAMPLE = "Foo" Public Sub Test() Application.VBE.ActiveVBProject.VBComponents.Item("Module1").CodeModule.ReplaceLine 1, _ "Public Const EXAMPLE = ""Bar""" Debug.Print EXAMPLE '<-- prints Foo End Sub
If you attempt to step through this with the debugger, you’ll get the same message because the code in the VBE no longer matches what is being executed in the context of the debugger. Consider the following code:
'Module1 Public Const EXAMPLE = "Bar" Public Sub Test() With Application.VBE.ActiveVBProject.VBComponents.Item("Module1").CodeModule .DeleteLines 1, .CountOfLines End With Debug.Print "Where am I?" '<-- this will still execute. End Sub
If you step through this using F8, what line is the debugger supposed to highlight after you delete all of the code?
So, the X to your Y is to simply not attempt to run self modifying code. A string that needs to change is not a constant – it is a variable. My recommendation would be to make it a property, give it a default value, and set it at run-time as needed:
'mod00Admin Private Const DEFAULT_DB As String = "C:\Foo\Bar.accdb" Private activeQuoteDB As String Public Property Let QuoteDB(rhs As String) activeQuoteDB = rhs End Property Public Property Get QuoteDB() As String If activeQuoteDB = vbNullString Then QuoteDB = DEFAULT_DB Else QuoteDB = activeQuoteDB End If End Property '... Public Sub AB() LoadQuoteDetails2.Automation mod00Admin.QuoteDB = "A:.0 Projects\P0445 Ireland Commercial Raters Analysis Rate Assessor\ROI Fleet Rater\Quote Database\Quote DB June 18.accdb" CalcTariffPrem End Sub