You can use a SQL statement too to accomplish this one.
(您也可以使用SQL语句来完成这一操作。)
For this to work you'll need to make sure you have column headers, add a reference to Microsoft ActiveX Data Object 2.8 Library
or greater, and the Microsoft.ACE.OLEDB.12.0
driver installed (it comes with MS Access). (为此,您需要确保具有列标题,添加对Microsoft ActiveX Data Object 2.8 Library
或更高版本的引用,并安装了Microsoft.ACE.OLEDB.12.0
驱动程序(MS Access附带)。)
Make sure to update the sheet references, as I made up a contrived example.
(请确保更新工作表引用,因为我做了一个人为的示例。)
Option Explicit
Public Sub GetTopTenValues()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet3")
Dim outsheet As Worksheet: Set outsheet = ThisWorkbook.Worksheets("Sheet4")
Dim lastRow As Long
Dim lastCol As Long
Dim conn As ADODB.Connection: Set conn = New ADODB.Connection
Dim rs As ADODB.Recordset: Set rs = New ADODB.Recordset
Dim sql As String
Dim i As Long
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties='Excel 12.0 Xml;HDR=YES';"
conn.Open
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
For i = 2 To lastCol
sql = "Select top 10 [names], [" & ws.Cells(1, i).Value2 & "] from [Sheet3$] order by [" & ws.Cells(1, i).Value2 & "] desc"
rs.Open sql, conn
lastRow = outsheet.Cells(outsheet.Rows.Count, "A").End(xlUp).Row + 1
outsheet.Range("A" & lastRow).CopyFromRecordset rs
rs.Close
Next
conn.Close
End Sub
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…