Reset of variables after using the InsertLines method inserting lines of code in a module with access 2021

jacky Perpète 61 Reputation points
2023-02-22T09:18:55.91+00:00

Hello,

Access 2021 version.

When inserting a line of code using the <InsertLines> method in a VBA module, I noticed that all program variables were reset after execution. When the line of code using the <InsertLines> method is commented out, the problem does not arise.

Here is illustrated the result of a small test program.

CreateCode

Here is the test code in the form.

Option Compare Database
Option Explicit

Dim MyVariableForm As String
'Ajouter la référence <Microsoft Visual Basic for Applications Extensibility 5.3>

Private Sub cmdCode_Click()

Dim codeModuleProject As VBIDE.CodeModule
Dim positionLine As Long, idNameprocedure As Long
Dim codeVBA As String

Set codeModuleProject = VBE.VBProjects(1).VBComponents("AddCode").CodeModule
'Se positionne sur une nouvelle ligne en dessous du module
positionLine = codeModuleProject.CountOfLines + 1

'Crée le début de la procédure
idNameprocedure = Timer * 100
codeVBA = vbCrLf & "Public sub Essai" & idNameprocedure & "()"

'Ajoute la fin de la procédure
codeVBA = codeVBA & vbCrLf & vbCrLf & "End Sub"

'Ajoute le code et le visualise
codeModuleProject.InsertLines positionLine, codeVBA
VBE.VBProjects(1).VBComponents(codeModuleProject.Name).Activate
VBE.ActiveCodePane.SetSelection positionLine + 1, 1, positionLine + 1, 1
VBE.ActiveCodePane.Show

End Sub

Private Sub cmdInitVariable_Click()

'Initialise les variables publics et du formulaire
MyVarPublic1 = 100
MyVarPublic2 = True
MyVariableForm = "Form variable"
Me.txtVariable1 = MyVarPublic1
Me.txtVariable2 = MyVarPublic2
Me.txtVariable3 = MyVariableForm

End Sub

Private Sub cmdRead_Click()

'Affiche les valeurs des variables publics et du formulaire
Me.txtVariable1 = MyVarPublic1
Me.txtVariable2 = MyVarPublic2
Me.txtVariable3 = MyVariableForm

End Sub

Here are the public variables in the Parameters module.

PublicVar

Here is the code created in the AddCode module by the InsertLines method.

Code

Is there a solution to this problem?

Access
Access
A family of Microsoft relational database management systems designed for ease of use.
400 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,997 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.