之前的文章
《Excel·VBA二维数组组合函数、组合求和》
,可以对A-B列每行选择一种状态,返回所有状态的组合,对“原值”依次累加C-D列数值,判断是否符合F2:F3所需结果。以下代码调用了combin_arr2d函数,如需使用代码需复制
Sub 穷举开关状态1()
Dim arr, c, d, v, v1, v2, brr, b, sum1, sum2, write_col&, i&
arr = [a2:b9]: v = [f1]: v1 = [f2]: v2 = [f3]
write_col = 8
c = [c2].Resize(8, 1): c = WorksheetFunction.Transpose(c)
d = [d2].Resize(8, 1): d = WorksheetFunction.Transpose(d): tm = Timer
brr = combin_arr2d(arr)
For Each b In brr
sum1 = v: sum2 = v
For i = 1 To UBound(b)
If b(i) = "是" Then
If Len(c(i)) Then sum1 = Application.Evaluate(sum1 & CStr(c(i)))
If Len(d(i)) Then sum2 = Application.Evaluate(sum2 & CStr(d(i)))
End If
If Abs(Round(sum1 - v1, 6)) < (0.1 ^ 6) And Abs(Round(sum2 - v2, 6)) < (0.1 ^ 6) Then
Cells(2, write_col).Resize(UBound(b), 1) = WorksheetFunction.Transpose(b)
write_col = write_col + 1
End If
Debug.Print "累计用时:" & Format(Timer - tm, "0.00")
End Sub
注意:从上到下运算累计计算结果,并非将计算式叠加后一次性计算结果
开关只有“是/否”2种状态,那么也可以用0和1表示,这与二进制数一样,之前的文章《python从数组中找出所有和为M的组合》,采用过这种方法查找组合求和的结果,那么本问题也可尝试
n个元素的全组合总数=2 ^ n,故8个元素的全组合数为256个,即0-255转化为二进制数(例如255的二进制数为“11111111”,表示8个元素全部选择)
Sub 穷举开关状态2()
Dim c, d, v, v1, v2, s$, s1$, sum1, sum2, write_col&, i&, x&
v = [f1]: v1 = [f2]: v2 = [f3]: Dim res(1 To 8)
write_col = 8
c = [c2].Resize(8, 1): c = WorksheetFunction.Transpose(c)
d = [d2].Resize(8, 1): d = WorksheetFunction.Transpose(d): tm = Timer
For x = 1 To 2 ^ 8 - 1
s = CStr(WorksheetFunction.Dec2Bin(x)): s = Format(s, "00000000")
sum1 = v: sum2 = v
For i = 1 To Len(s)
s1 = Mid(s, i, 1): res(i) = IIf(s1 = "1", "是", "否")
If s1 = "1" Then
If Len(c(i)) Then sum1 = Application.Evaluate(sum1 & CStr(c(i)))
If Len(d(i)) Then sum2 = Application.Evaluate(sum2 & CStr(d(i)))
End If
If Abs(Round(sum1 - v1, 6)) < (0.1 ^ 6) And Abs(Round(sum2 - v2, 6)) < (0.1 ^ 6) Then
Cells(2, write_col).Resize(UBound(res), 1) = WorksheetFunction.Transpose(res)
write_col = write_col + 1
End If
End Sub
此种方法不足之处:十进制转二进制Dec2Bin函数,取值范围太小,超过511就不适用;元素个数变化时需要修改第3、5-8行的代码,较为麻烦
同样的原始数据,输出结果相同,但顺序不同
Sheets("sheet1").Select
Row = Sheets("sheet1").UsedRange.Rows.count
col = Sheets("sheet1").UsedRange.Columns.count
ReDim arr(1 To Row, 1 To 6)
arr = Range("a1:F" & Row)
arr = bubblesort(arr, 0, 2, 2)
Range("j1:O" &...
withEvents
可选。该关键字指定varname是对象变量,用于响应触发一个ActiveX对象。WithEvents只在类模块有效。使用它你可以定义多个独立的对象,但是不能使用该关键字创建数组,也不能与New关键字一起使用。
varname
###VBA动态数组简单应用
动态数组在VBA中,用于筛选大数据是比较好用的.当一行数据满足筛选要求时,将该行数据写入到新的数组中,逐维增加,最后再将这个新的数组输出到表格.
动态数组和一静态数组定义不同
静态数组定义:
dim arr
动态数组定义:
dim arr()
重新定义动态数组:
redim arr(1 to 5,2 to x)
保留原数组中的内容重新定义动态数组:
redim preserve arr(1 to 5, 2 to x)
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数组长度:");
int n = scanner.nextInt();