Change VBA coding with VBA Coding

前端 未结 1 347
情书的邮戳
情书的邮戳 2020-12-22 01:13

I need to change a constant, that references a web address. Our ADI templates have a new server path and it would be easier to update the code than download all new template

相关标签:
1条回答
  • 2020-12-22 01:23

    First, you need to add a reference to the Microsoft Visual Basic for Applications Extensibility 5.3 library.

    Click Tools>>References>> Microsoft Visual Basic for Applications Extensibility 5.3

    vba project references

    Then you need to open the workbook containing the module you want to update. This means that you cannot make this update while users have the workbook open.

    Workbook.Open filePath
    

    Next, you'll need to loop through each code module in the workbook, looking for the constant you're looking to change.

    Sub replaceConstant()
        Dim project As VBIDE.VBProject
        For Each project In Application.VBE.VBProjects
    
            Dim codeMod As VBIDE.CodeModule
            Dim component As VBIDE.VBComponent
    
            For Each component In project.VBComponents
    
                If component.Name <> "TheVeryUniqueNameOfTheCodeModuleWhereThisCodeResides" Then
    
                    Set codeMod = component.CodeModule
    
                    Dim startline As Long
                    startline = 1 'find takes startline in byref and uses it as an output parameter.
    
                    codeMod.Find Target:="Const SERVLET_PATH = ""http://webaddress.com""", _
                        startline:=startline, startcolumn:=1, endline:=codeMod.CountOfLines, endcolumn:=1
    
                    codeMod.ReplaceLine startline, "Const SERVLET_PATH = ""http://webaddress1.com"""
    
    
                End If
            Next component
    
        Next project
    End Sub    
    

    The above code works because:

    The Find method accepts ByRef Long parameters. Upon input, these parameters specify the range of lines and column to search. On output, these values will point to the found text.

    CPearson.com - Programming the VBA Editor

    Of course, you'll need to do this for every workbook you want to change. This could take some time.

    Further Resources:

    • CodeModule Object
    • Find Method
    • ReplaceLine Method
    0 讨论(0)
提交回复
热议问题