vbafind前3个值运行时错误

我想从列表中获取前3个值,所有数值,在VBA中使用大函数。 我的代码有一个错误,当我运行它,运行时错误1004无法获得工作表function类的Large属性。 不知道如果我定义错误。 我在评论部分尝试了两种方法,仍然得到相同的错误。 我也试图定义rng1,rng2作为变种,因为我不知道如何在vba中定义数组,但同样的错误。

列S的值是我想要的前3或最大的3,列G有相应的值。 在位置方面,我想粘贴前3在w1,x1和y1和相应的值在w2,x2和y2。 没有关系,所以不必担心打破平局。

Sub test() Dim ws As Worksheet Dim lr As Long Dim rng1, rng2 As Range Set ws = Worksheets("policies") lr = ws.Cells(Cells.Rows.Count, "A").End(xlUp).Row Set rng1 = ws.Range("S3:S" & lr) Set rng2 = ws.Range("G3:G" & lr) For i = 23 To 25 For c = 1 To 3 'Worksheets("policies").Cells(1, i).Value = Application.WorksheetFunction.Large(rng1, c) ws.Cells(1, i).Value = Application.WorksheetFunction.Large(rng1, c) Next c For j = 23 To 25 ws.Cells(2, j).Value = Application.WorksheetFunction.Index(rng2, Application.WorksheetFunction.Match(ws.Cells(1, i).Value, rng1, 0)) Next j Next i End Sub 

你的循环会覆盖前面的循环,你将会在每个单元中的第三大单元结束,你只需要一个循环:

 Sub test() Dim ws As Worksheet Dim rng1, rng2 As Range Dim i&, c& Set ws = Worksheets("policies") lr = ws.Cells(Cells.Rows.count, "A").End(xlUp).Row Set rng1 = ws.Range("S3:S" & lr) Set rng2 = ws.Range("G3:G" & lr) For i = 23 To 25 c = 26 - i ws.Cells(1, i).Value = Application.WorksheetFunction.Large(rng1, c) ws.Cells(2, i).Value = Application.WorksheetFunction.Index(rng2, Application.WorksheetFunction.Match(ws.Cells(1, i).Value, rng1, 0)) Next i End Sub 

我testing了这一点,它适用于简单的数据:

在这里输入图像说明