如何从宏记录器改进代码?

时间:2013-04-06 11:35:54

标签: excel vba for-loop border

我在宏记录器中使用此代码并在for循环中添加。

如果可能的话,怎样才能做得更好?

我想要使用2003年和2010年。

Range(Cells(2, 2).Address, Cells(5, 5).Address).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlDouble
    .Color = -16777216
    .Weight = xlThick
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlDouble
    .Color = -16777216
    .Weight = xlThick
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlDouble
    .Color = -16777216
    .Weight = xlThick
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlDouble
    .Color = -16777216
    .Weight = xlThick
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .ColorIndex = xlAutomatic
    .Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
    .LineStyle = xlContinuous
    .ColorIndex = xlAutomatic
    .Weight = xlThin
End With

2 个答案:

答案 0 :(得分:3)

继上面我的评论,其中包括link,其中详细讨论了避免.Select

这是我的three美分。

:一种。声明你的对象/变量

声明变量/对象后,工作变得更容易。这可确保您不必键入重复的代码。例如

Range(Cells(2, 2).Address, Cells(5, 5).Address).THIS
Range(Cells(2, 2).Address, Cells(5, 5).Address).THAT
Range(Cells(2, 2).Address, Cells(5, 5).Address).THIS

etc...

<强> B中。确保您完全符合对象资格并使用它们

这是导致错误的最常见原因。考虑这一行。

Range(Cells(2, 2).Address, Cells(5, 5).Address)

这里Excel假设您正在使用当前工作表。如果你不是,那该怎么办?见这个例子

Sheets(2).Range(Cells(2, 2).Address, Cells(5, 5).Address)

此处Cells()对象不是完全限定的,可能会导致错误。见post

<强>℃。删除额外/重复代码

Excel常量xlEdgeLeftxlEdgeTopxlEdgeBottomxlEdgeRight等每个都等于一个数字,而且也是按递增顺序排列的。如果您在立即窗口中键入它,那么您可以检查它的值

'~~> This will give you 7
?xlEdgeLeft

因此,我们实际上可以利用这一点并缩短代码。

请参阅以下代码

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim i As Long

    '~~> Change this to the relevant worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        Set rng = .Range(.Cells(2, 2).Address, .Cells(5, 5).Address)

        With rng
            .Borders(xlDiagonalDown).LineStyle = xlNone
            .Borders(xlDiagonalUp).LineStyle = xlNone

            For i = 7 To 10
                'xlEdgeLeft = 7 : xlEdgeTop = 8 : xlEdgeBottom = 9
                'xlEdgeRight = 10
                With .Borders(i)
                    .LineStyle = xlDouble: .Color = -16777216: .Weight = xlThick
                End With
            Next

            For i = 11 To 12
                'xlInsideVertical = 11 : xlInsideHorizontal = 12
                With .Borders(i)
                    .LineStyle = xlContinuous: _
                    .ColorIndex = xlAutomatic: .Weight = xlThick
                End With
            Next
        End With
    End With
End Sub

答案 1 :(得分:1)

尝试使用像这样的范围

Range(Cells(2, 2).Address, Cells(5, 5).Address).Borders(xlEdgeBottom).LineStyle = xlDouble

为每个边框边缘和颜色等执行此操作