Excel VBA Module Not Updating While Running

后端 未结 2 641
故里飘歌
故里飘歌 2020-12-22 04:30

I have 2 modules, the main module updates the other module while running, and runs that module every time it updates.

The problem is that the other module seems to n

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-22 05:13

    While giving a +1 to the perils of dynamically writing code, changing the method name seems to force a recompile:

    Public Sub AddNewWorkBookTEST()
    
        Dim nextline As Long, LastUsedRowList As Long
        Dim CodeString As String
        Dim x As Long
        Dim KWATT As Double
    
    
        Dim folderPath As String
        folderPath = Application.ActiveWorkbook.Path
    
        LastUsedRowList = sheet4.Cells(Rows.Count, 1).End(xlUp).Row
    
        For x = 1 To LastUsedRowList
            KWATT = sheet4.Cells(x, 1)
            Debug.Print KWATT
            CodeString = CodeStringGenerator(x, KWATT)
            ''Update the module code
            With ActiveWorkbook.VBProject.VBComponents("MyNewTest").CodeModule
                .DeleteLines 1, .CountOfLines
                nextline = .CountOfLines + 1
                .InsertLines nextline, CodeString
            End With
            Application.Run "MyNewTest.SortedArray_" & x, x
        Next x
    End Sub
    
    
    Function CodeStringGenerator(x As Long, KWATT As Double) As String
        CodeStringGenerator = "'Option Explicit" & vbCrLf & _
        "Public Function SortedArray_" & x & "(ItemsCounter As Long) As Variant()" & vbCrLf & vbCrLf _
        & "Dim TempSortedArray() As Variant" & vbCrLf _
        & "Sheet4.Cells(ItemsCounter, 2) = " & KWATT + 5 & vbCrLf _
        & "End Function" & vbCrLf
    End Function
    

提交回复
热议问题