vba找到前三个值运行时错误

时间:2016-12-30 17:15:34

标签: excel vba excel-vba

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

列S具有我想要获得前3或最大3的值,而列G具有相应的值。位置方面,我想在w1,x1和y1中粘贴前3个,在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

1 个答案:

答案 0 :(得分:1)

你的循环将覆盖前一个循环,你将最终得到每个单元格中只有一个循环的第三大循环:

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

我对此进行了测试,它适用于简单的数据:

enter image description here