VBE中的ReplaceLine方法仅替换部分行

时间:2015-06-22 19:34:31

标签: excel-vba vbe vba excel

在回答this问题时,我认为编写一个自动替换看起来像

的行的VBE宏会很有趣
DimAll a, b, c, d As Integer

通过

Dim a As Integer, b As Integer, c As Integer, d As Integer

在我的初稿中,我只想修改一个选定的行。在建立适当的引用以获得VBE对象模型(参见http://www.cpearson.com/excel/vbe.aspx)并玩了一下之后我想出了:

Function ExpandDim(codeLine As String) As String
    Dim fragments As Variant
    Dim i As Long, n As Long, myType As String
    Dim last As Variant
    Dim expanded As String

    If UCase(codeLine) Like "*DIMALL*AS*" Then
        codeLine = Replace(codeLine, "dimall", "Dim", , , vbTextCompare)
        fragments = Split(codeLine, ",")
        n = UBound(fragments)
        last = Split(Trim(fragments(n)))
        myType = last(UBound(last))
        For i = 0 To n - 1 'excludes last fragment
            expanded = expanded & IIf(i = 0, "", ",") & fragments(i) & " As " & myType
        Next i
        expanded = expanded & IIf(n > 0, ",", "") & fragments(n)
        ExpandDim = expanded
    Else
        ExpandDim = codeLine
    End If
End Function

Sub DimAll()
    Dim myVBE As VBE
    Dim startLine As Long, startCol As Long
    Dim endLine As Long, endCol As Long
    Dim myLine As String
    Set myVBE = Application.VBE
    myVBE.ActiveCodePane.GetSelection startLine, startCol, endLine, endCol
    myLine = myVBE.ActiveCodePane.CodeModule.Lines(startLine, 1)
    Debug.Print ExpandDim(myLine)
    myVBE.ActiveCodePane.CodeModule.ReplaceLine startLine, ExpandDim(myLine)
End Sub

在我的另一个代码模块中:

Sub test()
    DimAll a, b, c, d As Integer
    Debug.Print TypeName(a)
    Debug.Print TypeName(b)
    Debug.Print TypeName(c)
    Debug.Print TypeName(d)
End Sub

这是奇怪的部分。当我突出显示开始DimAll a的行,并调用我的笨拙命名的子DimAll时,在我看到的即时窗口中

Dim a As Integer, b As Integer, c As Integer, d As Integer

这是预期的,但在代码模块本身中,行被更改为

Dim a, b, c, d As Integer

DimAll已被Dim取代 - 但该线的其余部分未经修改。我怀疑逗号混淆了ReplaceLine方法。关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:4)

当我使用调试器运行时,myLine会在两次调用之间更改值。 DimAll第二次成为Dim

这是因为您在codeLine内输入主要If条件后,您将替换ExpandDim Function的值。

在该函数中创建一个新变量,你应该没问题......或者传递它ByVal并且你很好:

Function ExpandDim(ByVal codeLine As String) As String