利用Excel VBA实现批量数据分组转置


问题:如上图所示,按lon,lat分组,再进行转置。

Sub admin()
    Dim conn, xRs, xFd
    Set conn = CreateObject("ADODB.Connection")
    conn.Open "Provider=Microsoft.Jet.Oledb.4.0;" & _
              "Extended Properties= 'Excel 8.0;hdr=yes;IMEX=1' ;" & _
              "Data Source=" & ThisWorkbook.FullName
    Set xRs = CreateObject("ADODB.RecordSet")
        sSql = " Transform Sum( [Tas_t] ) Select [lon] , [lat] From [Sheet1$A:D] Group By [lon] , [lat] Pivot [Year] "
        xRs.Open sSql, conn, 1, 3
        i = 0
        For Each xFd In xRs.Fields
            Range("F1").Offset(0, i) = xFd.Name
            i = i + 1
        Next
        Range("F2").CopyFromRecordset xRs
        xRs.Close
        conn.Close
    Set xRs = Nothing
    Set conn = Nothing
End Sub


你可能感兴趣的:(利用Excel VBA实现批量数据分组转置)