Ok...下面的行将数组 myArr 的内容放在单元格 A1 中
sh.Range("A1").Resize(cnt, 7).Value = myArr
以下是上述行输出的一些示例记录
18 5 1 23 15 7 6
23 5 3 10 18 20 15
19 10 25 12 21 15 23
10 14 11 9 7 25 20
24 15 23 20 11 17 2
7 15 3 16 24 22 13
14 4 15 13 6 23 2
20 11 22 24 14 3 6
17 5 13 15 19 6 22
9 13 15 7 24 3 6
在这一行之前,我需要一个条件,但不确定如何编写语法。我想将第一个元素 (lbound
) 的所有 7 个值相加并检查总和并对所有元素执行此操作,直到 ( ubound
)。并且仅在总数等于 100 时才运行上述行
解决第一个查询后,我还有第二个查询仅列出有关元素总数为 100 的计数,有多少元素的总和为 80 等等......通过添加另一个从第一个数组获取信息的数组。计数将在 75 到 125 之间。预期输出应为
75 1
76 0
77 2
.
.
.
125 1
这就是我正在尝试的
Sub foo()
Dim myArr(1 To 10)
Dim cnt As Integer, i As Integer
myArr(1) = "18,5,1,23,15,7,6"
myArr(2) = "23,5,3,10,18,20,15"
myArr(3) = "19,10,25,12,21,15,23"
myArr(4) = "10,14,11,9,7,25,20"
myArr(5) = "24,15,23,20,11,17,2"
myArr(6) = "7,15,3,16,24,22,13"
myArr(7) = "14,4,15,13,6,23,2"
myArr(8) = "20,11,22,24,14,3,6"
myArr(9) = "17,5,13,15,19,6,22"
myArr(10) = "9,13,15,7,24,3,6"
For i = 1 To UBound(myArr)
With Application.WorksheetFunction.Sum = .Sum(.Index(myArr, i, 0))
'if ....
'....
'endif
End With
Range("A1").Resize(cnt, 7).Value = myArr
End Sub
聊天的第 1 部分和第 2 部分:评论移至聊天这会将您的字符串拆分为其元素,转换为整数和总和。然后它执行检查,以查看是否 = 100,如果是,则添加到一个数组中,然后可以写出到工作表中。我不禁想到可能有比使用这么多数组更有效的方法,但还没有想到。
Sub foo()
Dim myArr(1 To 10)
Dim TotalsArr(1 to 10)
Dim cnt As Integer, i As Integer
myArr(1) = "18,5,1,23,15,7,6"
myArr(2) = "23,5,3,10,18,20,15"
myArr(3) = "19,10,25,12,21,15,23"
myArr(4) = "10,14,11,9,7,25,20"
myArr(5) = "24,15,23,20,11,17,2"
myArr(6) = "7,15,3,16,24,22,13"
myArr(7) = "14,4,15,13,6,23,2"
myArr(8) = "20,11,22,24,14,3,6"
myArr(9) = "17,5,13,15,19,6,22"
myArr(10) = "9,13,15,7,24,3,6"
Dim tempArr as Variant
Dim Val as Variant
Dim Total as Long
Dim Counter As Long
Dim FinalArr()
第1部分:计算项目总数并检查是否= 100,然后添加到结果数组中。
Counter = 0
For i = LBound(myArr) to UBound(myArr)
Total = 0
tempArr = Split(myArr(i),",")
For Each Val in tempArr
Total = Total + Val
Next Val
If Total = 100 Then
ReDim Preserve FinalArr(Counter)
FinalArr(Counter) = myArr(i)
Counter = Counter + 1
End If
TotalsArr(i) = Total 'store totals for later use in dictionary
Next i
For i = LBound(FinalArr) to UBound(FinalArr)
Debug.Print FinalArr(i)
Next i
第 2 部分:获取每个不同总数的计数。 我们将使用字典来存储每个键的计数(总计),并在再次找到相同的键时覆盖,将一个添加到值(即计数)
Dim totalsDict As Scripting.Dictionary 'Tools > references > add in microsoft scripting runtime
Dim key as Variant
Set totalsDict = New Scripting.Dictionary
'If prepopulating with totals to check for in range 75 to 125 ( otherwise comment out next 3 code lines
For i = 75 to 125
totalsdict.Add i , 0
Next i
For i = LBound(TotalsArr) to UBound(TotalsArr)
totalsDict(TotalsArr(i)) = totalsDict(TotalsArr(i)) + 1 'will overwrite adding one to value
Next i
For Each key in totalsdict.Keys
Debug.print key, "," , totalsDict(key)
Next key
End Sub