在GetRows中转置行列

时间:2014-01-06 21:43:43

标签: mysql performance excel-vba adodb transpose

低于VBA代码完成了这项工作,但我在转置部分失去了3秒。

有没有办法可以获得相同的结果,或者在SQL查询或getrows过程中不会丢失3秒?

Sub LoadData()
Dim strCon, srtQry As String, tmpArray, tmpArray2, R As Variant, i, j As Long

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

strCon = "DRIVER={MySQL ODBC 5.2 ANSI Driver};" & _
        "SERVER=localhost;" & _
        "DATABASE=tbname;" & _
        "USER=root;" & _
        "PASSWORD=pass;" & _
        "Port=3306;" & _
        "Option=3"

cn.Open strCon

srtQry = "SELECT * FROM `tbname` WHERE `FileDay` = 20131220"

Set rs = cn.Execute(srtQry)

tmpArray = rs.GetRows

cn.Close

tmpArray2 = TransposeArray(tmpArray)

End Sub

TransposeArray:

Public Function TransposeArray(InputArr As Variant) As Variant

Dim RowNdx, ColNdx, LB1, LB2, UB1, UB2 As Long, tmpArray As Variant

LB1 = LBound(InputArr, 1)
LB2 = LBound(InputArr, 2)
UB1 = UBound(InputArr, 1)
UB2 = UBound(InputArr, 2)

ReDim tmpArray(LB2 To LB2 + UB2 - LB2, LB1 To LB1 + UB1 - LB1)

For RowNdx = LB2 To UB2
    For ColNdx = LB1 To UB1
        tmpArray(RowNdx, ColNdx) = InputArr(ColNdx, RowNdx)
    Next ColNdx
Next RowNdx

TransposeArray = tmpArray

End Function

2 个答案:

答案 0 :(得分:1)

您可以应用一些优化

  1. 声明:您需要指定每个变量
  2. 的数据类型
  3. 删除Redim
  4. 中的冗余计算
  5. 使用更紧凑的For循环结构
  6. 将变体指定为数组
  7. 影响最大:使用Sub而不是Function
  8. 这些将使Transpose的运行时间减少50%以上

    Public Sub TransposeArray(ByRef InputArr() As Variant, ByRef ReturnArray() As Variant)
        Dim RowNdx As Long, ColNdx As Long
        Dim LB1 As Long, LB2 As Long, UB1 As Long, UB2 As Long
    
        LB1 = LBound(InputArr, 1)
        LB2 = LBound(InputArr, 2)
        UB1 = UBound(InputArr, 1)
        UB2 = UBound(InputArr, 2)
    
        ReDim ReturnArray(LB2 To UB2, LB1 To UB1)
    
        For RowNdx = LB2 To UB2
        For ColNdx = LB1 To UB1
            ReturnArray(RowNdx, ColNdx) = InputArr(ColNdx, RowNdx)
        Next ColNdx, RowNdx
    
    End Sub
    

    像这样称呼

    TransposeArray tmpArray, tmpArray2
    

答案 1 :(得分:0)

知道这是古老的 - 但是如果您按照标签的建议使用 Excel - 那么您可能会发现 Application.WorksheetFunction.Transpose() 快得多(没有尝试过 - 但我相信这是一个很好的预感)< /p>