5

在回答这个问题时,我认为编写一个 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 方法。关于如何解决这个问题的任何想法?

4

1 回答 1

4

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

这是因为codeLine一旦您IfExpandDim Function.

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

Function ExpandDim(ByVal codeLine As String) As String
于 2015-06-22T19:54:39.463 回答