1

我使用宏记录器中的这段代码并在 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
4

2 回答 2

3

除了我上面的评论,其中包括一个详细讨论避免的链接.Select

这是我的three美分。

A. 声明你的对象/变量

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

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()对象不是完全限定的,可能会导致错误。看到这个帖子

C. 删去多余的/重复的代码

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

'~~> 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
于 2013-04-06T16:40:36.873 回答
1

尝试使用这样的范围

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

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

于 2013-04-06T12:48:35.640 回答