【问题标题】:Transpose rows column in GetRows转置 GetRows 中的行列
【发布时间】:2014-01-24 10:31:50
【问题描述】:

下面的 VBA 代码可以完成这项工作,但我在转置部分损失了大约 3 秒。

有没有一种方法可以在不丢失 3 秒的情况下在 SQL 查询或 getrows 过程中获得相同的结果?

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

转置数组:

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

【问题讨论】:

  • 原谅我的无知,TransposeArray 是什么?
  • @Doug Glancy。我的常用 excel-vba 数组转置代码版本。将编辑和包含。

标签: mysql excel vba transpose adodb


【解决方案1】:

您可以应用一些优化

  1. 声明:需要指定每个变量的数据类型
  2. 删除Redim中的冗余计算
  3. 使用更紧凑的 For 循环结构
  4. 将您的变体指定为数组
  5. 对于最大的影响:使用Sub 而不是Function

这些加在一起将使 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

【讨论】:

  • 太棒了!但我有一个编译错误:'类型不匹配:预期数组或用户定义类型'。我错过了什么?
  • 当我打电话给TransposeArray tmpArray, tmpArray2时,突出显示tmpArray
  • 有效!当我将数组调暗时,我所要做的就是包含'()',以便Dim tmpArray(), tmpArray2() As Variant。猜猜这就是“4-将您的变体指定为数组”的意思。不是我最初寻找的解决方案,但确实加快了 50%!
  • 感谢这个答案。清理自己的代码是我们都需要做得更好的事情。
【解决方案2】:

知道这是古老的 - 但如果你在 Excel 中正如你的标签所建议的那样 - 那么你可能会发现 Application.WorksheetFunction.Transpose() 快得多(没有尝试过 - 但我相信这是一个很好的预感)

【讨论】:

    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 2022-11-17
    • 2023-03-27
    相关资源
    最近更新 更多