gpt4 book ai didi

excel - 如何改进宏记录器的代码?

转载 作者:行者123 更新时间:2023-12-04 21:40:14 25 4
gpt4 key购买 nike

就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the help center寻求指导。




9年前关闭。




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

最佳答案

除了我上面的评论,其中包括 link其中详细讨论了避免.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()对象不是完全限定的,可能会导致错误。看到这个 post

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

Excel 常量 xlEdgeLeft , xlEdgeTop , xlEdgeBottom , xlEdgeRight等每个都等于一个数字,而且也是按递增顺序排列的。如果您在立即窗口中键入它,那么您可以检查它的值
'~~> 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

关于excel - 如何改进宏记录器的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15850430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com