MS Excel:macros查询数组
可以在第A列第二行中说,我有45分,而在B列,我有得到那个分数的人数。 那么我想要做的就是在D列上输出那个得分X的次数。 X = repitition。
在这个例子中5人得了45分,所以在D列我想插入5分45.然后我在A列中看到:Row2 3人得到了46分,然后在最后45分,在列DI想要追加46次3次..等等..
有人能告诉我如何做到这一点?
干得好:
Sub test_scores_repitition() 'run with test scores sheet active r = 1 dest_r = 1 Do While Not IsEmpty(Range("a" & r)) If IsEmpty(Range("b" & r)) Then Range("b" & r).Value = 0 'if there's no quantity listed for a score, it assumes zero For i = 1 To Range("b" & r).Value Range("d" & dest_r).Value = Range("a" & r).Value dest_r = dest_r + 1 Next i r = r + 1 Loop End Sub
macros答案:
Sub WriteIt() Dim lrow As Long Dim WriteRow As Long Dim EachCount As Long Dim ReadRow As Long ' find last in list of numbers lrow = Range("A1").End(xlDown).Row 'start at 2 because of headers WriteRow = 2 ReadRow = 2 While ReadRow <= lrow For EachCount = 1 To Cells(ReadRow, 2) 'repeat the number of times in column B Cells(WriteRow, 4) = Cells(ReadRow, 1) 'the number in column A WriteRow = WriteRow + 1 Next ReadRow = ReadRow + 1 'and move to the next row Wend 'finish when we've written them all End Sub
有可能是一个公式,只是没有真正推荐,因为它看起来很有用,而且很难解释。 它使用Microsoft公式来计算上述数据中唯一项目的数量,一旦计算出上面的数字,它就会移到下一个数字。 公式不知道在哪里停止,并且在数据用完时将置0
。
在D2中,把=A2
在D3中,并抄下来,放
=IF(COUNTIF($D$2:D2,OFFSET($A$1,SUM(IF(FREQUENCY($D$2:D2,$D$2:D2)>0,1)),0))<OFFSET($B$1,SUM(IF(FREQUENCY($D$2:D2,$D$2:D2)>0,1)),0),OFFSET($A$1,SUM(IF(FREQUENCY($D$2:D2,$D$2:D2)>0,1)),0),OFFSET($A$1,SUM(IF(FREQUENCY($D$2:D2,$D$2:D2)>0,1))+1,0))