[英]Limiting value of elements in an array (VBA)
I have an array of numbers, say [1 2 3 4 5 6 7 8 9 10]
and I want to set a limiting value that all numbers over this value are set to - eg.我有一个数字数组,比如
[1 2 3 4 5 6 7 8 9 10]
,我想设置一个限制值,该值上的所有数字都设置为 - 例如。 a limiting value of 5 would produce [1 2 3 4 5 5 5 5 5 5]
.极限值为 5 将产生
[1 2 3 4 5 5 5 5 5 5]
。
I'm looking to do this on a much larger scale and I need to loop through a large number of times;我希望在更大的范围内执行此操作,并且需要多次循环; what's the most efficient a least resource-hungry method of doing this?
这样做的最有效的资源最少的方法是什么? I could loop over it but is there an in-built/more efficient way?
我可以遍历它,但有没有内置/更有效的方法?
Thanks in advance!提前致谢!
Add a class to your project that only allows values to a preset maximum.将一个类添加到您的项目中,该类只允许使用预设最大值的值。
Right click ThisWorkbook in the VBE's Project Explorer and choose Insert ► Class module.在 VBE 的 Project Explorer 中右键单击ThisWorkbook ,然后选择 Insert ► Class module。 Paste the following into the new code sheet titled something like Book1 - Class1 (Code) .
将以下内容粘贴到名为Book1 - Class1 (Code)的新代码表中。
Option Explicit
Private pVAL As Long
Private Const maxVAL As Long = 5 'set the maximum value here
Public Property Get val() As Long
val = pVAL
End Property
Public Property Let val(Value As Long)
If Value > maxVAL Then
pVAL = maxVAL
Else
pVAL = Value
End If
End Property
The maximum allowed value is set by a const
at the top of the page.最大允许值由页面顶部的
const
设置。 This allows you to change it in one place rather than searching for a hard-coded value in several places.这允许您在一个地方更改它,而不是在多个地方搜索硬编码值。 With an eye to your sample data, I've used a
long
type.着眼于您的示例数据,我使用了
long
类型。 You may wish to switch to another numerical variable type declaration.您可能希望切换到另一个数值变量类型声明。 When that has been pasted in, open the VBE's Properties window ( F4 ) and rename the class.
粘贴后,打开 VBE 的属性窗口 ( F4 ) 并重命名该类。 My example uses maxVAL .
我的示例使用maxVAL 。
In a module sheet, paste the following test code.在模块表中,粘贴以下测试代码。
Sub classTest()
Dim a As Long, mVals() As New maxVAL, sVal As New maxVAL
sVal.val = 3
Debug.Print sVal.val
sVal.val = 11
Debug.Print sVal.val
ReDim mVals(1 To 10)
For a = LBound(mVals) To UBound(mVals)
mVals(a).val = a
Next a
For a = LBound(mVals) To UBound(mVals)
Debug.Print mVals(a).val
Next a
End Sub
Run the sub and check the VBE's Immediate window for the results.运行 sub 并检查 VBE 的立即窗口以获取结果。 They should be similar to the following.
它们应该类似于以下内容。
classTest
3
5
1
2
3
4
5
5
5
5
5
5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.