在Excel的VBA中提取具有重复出现的数组的最大值
我有一个表,它有重复的索引,如图所示: 我想得到每个指数的时间1/2的最高值,苹果,香蕉 我的代码如下:在Excel的VBA中提取具有重复出现的数组的最大值,excel,vba,max,repeat,Excel,Vba,Max,Repeat,我有一个表,它有重复的索引,如图所示: 我想得到每个指数的时间1/2的最高值,苹果,香蕉 我的代码如下: dim i as integer, j as integer For i=2 to 4 j=2 While Cells(i,6)=Cells(j,2) if Cells(j,3) > Cells(i,7) then Cells(i,7) = Cells(j,3) end if
dim i as integer, j as integer
For i=2 to 4
j=2
While Cells(i,6)=Cells(j,2)
if Cells(j,3) > Cells(i,7) then
Cells(i,7) = Cells(j,3)
end if
if Cells(j,4) > Cells(i,8) then
Cells(i,8) = Cells(j,4)
end if
Wend
Next i
因此,我们的想法是遍历唯一的名称,然后遍历名称的每次出现,并检查它是否大于当前存储的时间
我知道有一些语法错误,因为每当我运行代码时,它不会改变我的工作表,我真的找不到关于如何替换VBA中的值的文档
因此,我想知道是否有一种更简单的方法来实现这一点,和/或寻求帮助以使用正确的语法。这完全可以在没有VBA的情况下完成。使用示例数据,在单元格J1中,我使用以下公式获得B列中唯一名称的数量:
=SUMPRODUCT((B2:B10<>"")/COUNTIF(B2:B10,B2:B10&""))
在单元格G2中,上下复制到H6的公式用于提取每个唯一名称的最大时间值:
=IF($F2="","",MAX(INDEX(($B$2:$B$10=$F2)*C$2:C$10,)))
右列F、G和H上填充的表格是结果:
或者,这可以通过透视表轻松完成。在B、C和D列中选择原始数据,然后转到Insert->Pivot Table。我选择将其放在同一工作表上,但如果愿意,您可以将其放在新工作表上。然后它会询问您的数据透视表字段,如图所示进行设置。注意,您需要将值从Count更改为Max:
然后会有一个数据透视表,显示相同的结果:
1.-你声明j=2但从不更改,我认为你必须从2行导航到10行,不是吗 2.-当您输入while语句时,您不会更改条件,因此。。。它将永远重复 我不确定你必须得到什么,所以请展示一个样品 +++++必须从表中删除-个值
dim i as integer, j as integer
For i=2 to 4
For j=2 to 10
if Cells(i,6)=Cells(j,2) then
if Cells(j,3) > Cells(i,7) then
Cells(i,7) = Cells(j,3)
end if
if Cells(j,4) > Cells(i,8) then
Cells(i,8) = Cells(j,4)
end if
end if
Next j
Next i
+++++您必须从表中删除-值我写错了,我的代码在while off表达式的末尾有j=j+1,但是在while的末尾也有j=j+1,您可以进入一个永恒的循环
dim i as integer, j as integer
For i=2 to 4
For j=2 to 10
if Cells(i,6)=Cells(j,2) then
if Cells(j,3) > Cells(i,7) then
Cells(i,7) = Cells(j,3)
end if
if Cells(j,4) > Cells(i,8) then
Cells(i,8) = Cells(j,4)
end if
end if
Next j
Next i