|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
终于把JSA改成VBA了,那段递归用VBA真是不好写。
- Dim res(), s, data()
- Sub main_VBA()
- data = Application.Transpose(Range("c4:c83"))
- Range("T11:V1000").ClearContents
- a = 5: b = 4: c = "9~11": d = "3~5": e = "2~3"
- fr1 = 筛选(a, b, c, d, e)
- Range("t11").Resize(UBound(fr1)) = Application.Transpose(fr1)
-
- a = 6: b = 3: c = "10~18": d = "2~5": e = "2~3"
- fr2 = 筛选(a, b, c, d, e)
- Range("U11").Resize(UBound(fr2)) = Application.Transpose(fr2)
-
- a = 3: b = 3: c = "14~24": d = "2~5": e = "0~0"
- fr3 = 筛选(a, b, c, d, e)
- Range("V11").Resize(UBound(fr3)) = Application.Transpose(fr3)
-
- ReDim frs(1 To UBound(fr1) * UBound(fr2) * UBound(fr3), 1 To 1)
- For Each x1 In fr1 '//符合条件的三个数组相合
- For Each x2 In fr2
- For Each x3 In fr3
- i = i + 1
- frs(i, 1) = x1 & "," & x2 & "," & x3
- Next x3, x2, x1
- Range("W11").Resize(UBound(frs)) = frs
- End Sub
- Function 筛选(a, b, c, d, e) '5个条件进行筛选
- For i = 1 To UBound(data)
- x = Val(data(i))
- If x \ 10 = a Then ss = ss & "," & data(i)
- Next
- nums = Split(Mid(ss, 2), ",")
- s = 0
- n = b
- ReDim res(1 To UBound(nums) ^ n)
- crr = Split(c, "~"): c1 = crr(0): c2 = crr(1)
- drr = Split(d, "~"): d1 = drr(0): d2 = drr(1)
- eerr = Split(e, "~"): e1 = eerr(0): e2 = eerr(1)
-
- Call dg(nums, n, "") '//生成res
- ReDim finalres(1 To UBound(res))
- For Each xx In res
- x = Split(Mid(xx, 2), ",")
- If test1(x, c1, c2) And test2(x, d1, d2) And test3(x, e1, e2) Then
- k = k + 1
- finalres(k) = Mid(xx, 2)
- End If
- Next
- ReDim f(1 To k)
- For i = 1 To k
- f(i) = finalres(i)
- Next
- 筛选 = f
- End Function
- Sub dg(nums, n, path) '递归生成,path=",1,2,3,4"样式,存入Res
- If Len(path) - Len(Replace(path, ",", "")) = n Then
- s = s + 1
- res(s) = path
- Exit Sub
- End If
- c = UBound(nums)
- For i = 0 To c
- x = nums(i)
- If Len(x) = 0 Then Exit Sub
- ReDim restnums(0 To c - i)
- For j = i + 1 To UBound(nums)
- restnums(j - i - 1) = nums(j)
- Next
- nextpath = path & "," & x
- Call dg(restnums, n, nextpath)
- Next
- End Sub
- Function test1(arr, t1, t2) As Boolean '组合结果个位数字和值是否在t1,t2之间
- If t1 = "" And t2 = "" Then test1 = True: Exit Function
- For Each x In arr
- n = n + Val(x) Mod 10
- Next
- If n >= Val(t1) And n <= Val(t2) Then test1 = True
- End Function
-
- Function test2(arr, t1, t2) As Boolean '组合结果个位数字跨度是否在t1,t2之间
- imax = 0: imin = 9
- If t1 = "" And t2 = "" Then test2 = True: Exit Function
- For Each x In arr
- t = Val(x) Mod 10
- If imax < t Then imax = t
- If imin > t Then imin = t
- Next
- n = imax - imin
- If n >= Val(t1) And n <= Val(t2) Then test2 = True
- End Function
- Function test3(arr, t1, t2) As Boolean '个位质数个数是否在t1,t2之间
- If t1 = "" And t2 = "" Then test3 = True: Exit Function
- For Each x In arr
- t = Val(x) Mod 10
- If t = 1 Or t = 2 Or t = 3 Or t = 5 Or t = 7 Then n = n + 1
- Next
- If n >= Val(t1) And n <= Val(t2) Then test3 = True
- End Function
复制代码 |
|