我正在寻找有关Excel VBA代码的一些最佳实践建议。我有内置在Excel中的报告,与其中用户选择了多个从下拉框和数据变量是基于经由SQL通过VBA的选择编译的位于前部的控制片材。
我拥有的代码非常简单,它将数据复制到工作表中并设置其格式。但是,在构建工作表时,当我逐步浏览工作表以确保代码正在执行我想要的工作时,它工作得很好。现在,我要执行代码,但不要在工作表中跳转。如果将其保留在控制表上,直到代码完成,它看起来会好得多。
但是,如果我不参考正在格式化的图纸,似乎无法执行相同的任务?
下面是一个工作表上用于复制数据和格式的代码。直到我需要它来选择Range("B5:K5").Select
为止,它都会起作用,然后在我的控制表上执行此操作。
On Error Resume Next
Sheets("Account Details").ShowAllData
Sheets("Account Details").Range("B5:K7500").Cells.ClearContents
Sheets("Account Details").Range("B5:K7500").Borders.LineStyle = xlNone
Sheets("Account Details").Range("B5").CopyFromRecordset rst2
Sheets("Account Details").Range("B5:K5").Select
Sheets("Account Details").Range(Selection, Selection.End(xlDown)).Select
Sheets("Account Details").Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Sheets("Account Details").Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Sheets("Account Details").Selection.Borders(xlEdgeLeft).LineStyle = xlContinuous
Sheets("Account Details").Selection.Borders(xlEdgeRight).LineStyle = xlContinuous
Sheets("Account Details").Selection.Borders(xlEdgeTop).LineStyle = xlContinuous
Sheets("Account Details").Selection.Borders(xlEdgeBottom).LineStyle = xlContinuous
Sheets("Account Details").Selection.Borders(xlInsideVertical).LineStyle = xlContinuous
Sheets("Account Details").Selection.Borders(xlInsideHorizontal).LineStyle = xlContinuous
Sheets("Account Details").Range("A1").Select
我想问的第二部分是关于VBA最佳实践的。并不是我知道如何,但是我不禁想到继续引用工作表有点混乱,并不是真正需要的。我已经尝试了几次With语句,但没有任何乐趣。
任何帮助将不胜感激。
谢谢!
答案 0 :(得分:1)
以您的代码为例
' On Error Resume Next 'NO - never use this, it doesn't deal with errors, just hides them - it will bite you eventually
With Sheets("Account Details")
IF .Autofiltermode Then .ShowAllData
with .Range("B5:K7500") 'note dot at beginning
.Cells.ClearContents
.Borders.LineStyle = xlNone
End With
Dim r as range
set r = .range("b5")
r.CopyFromRecordset rst2 'this is the first cell in b5:k7500
Set r = .Range(r, r.End(xlDown).end(xltoright)) 'redefine r to point to area
with r
.Borders(xlDiagonalDown).LineStyle = xlNone
.Borders(xlDiagonalUp).LineStyle = xlNone
.Borders(xlEdgeLeft).LineStyle = xlContinuous
.Borders(xlEdgeRight).LineStyle = xlContinuous
.Borders(xlEdgeTop).LineStyle = xlContinuous
.Borders(xlEdgeBottom).LineStyle = xlContinuous
.Borders(xlInsideVertical).LineStyle = xlContinuous
.Borders(xlInsideHorizontal).LineStyle = xlContinuous
End With 'end of with r
End With 'end if with sheet
'Sheets("Account Details").Range("A1").Select 'unnecessary