如何改善macroslogging器的代码?

我从macroslogging器使用这个代码,并添加一个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 

继我上面的评论,其中包括一个链接 ,详细谈论避免。select。

这是我的three钱。

A.声明你的对象/variables

当你声明你的variables/对象时,它变得更容易工作。 这确保您不必input重复的代码。 例如

 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常量xlEdgeLeftxlEdgeTopxlEdgeBottomxlEdgeRight等每个都等于一个数字,也是按照递增的顺序。 如果你在立即窗口中input,那么你可以检查它的值

 '~~> 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 

尝试使用这样的范围

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

为每个边框和颜色等做这个