节日,
我有一个问题要帮助我更多地了解 Excel VBA 如何有效地管理已在一个地方声明的已定义范围,以便很好地执行数据。只是想在更多地研究这个项目之前确定哪两个选项(我到目前为止知道)更好或不是首选的最佳实践。
我要解决的问题是制作一个小表,其中包含一组虚构供应商的许多故障,因此该表看起来像这样(对不起,它是原始形式)
“公司名称” “故障数”
“Be Cool Machine” 7
“Coolant Quarters” 5
“Little Water Coolants” 3
“Air Mover Systems” 7
“Generals Coolant” 5
“Admire Coolants” 4
我的第一个选项(常量字符串)是这个模块/公式,如下所示。
Option Explicit
Public Const CountofFailures As String = "J7:J12"
Sub btnRandom()
' Declaration of variables
Dim c As Range
' Provide a random number for failures across Suppliers
For Each c In ActiveSheet.Range(CountofFailures)
c.Value = Random1to10
Next c
End Sub
Function Random1to10() As Integer
'Ensure we have a different value each time we run this macro
Randomize
' Provide a random number from 1 to 10 (Maximum number of Failures)
Random1to10 = Int(Rnd() * 10 + 1)
End Function
第二个选项(定义名称)是这个模块/公式,如下所示。
Option Explicit
Sub btnRandom()
' Declaration of variables
Dim c As Range
Dim iLoop As Long
' Provide a random number for Suppliers with Defined Range
For Each c In ActiveWorkbook.Names("CountofFailures").RefersToRange
c.Value = Random1to10
Next c
End Sub
Function Random1to10() As Integer
'Ensure we have a different value each time we run this macro
Randomize
' Provide a random number from 1 to 10 (Maximum number of Failures)
Random1to10 = Int(Rnd() * 10 + 1)
End Function
任何建议 - 如果这有帮助,我稍后会做一个宏计时器测试?
如果我将单元格中列出的范围作为值获取,是否还有第三种选择?我还没有看到在实践中执行此操作的代码?