Excel VBA CopyFromRecordset水平?

时间:2013-01-24 11:37:42

标签: excel vba

我找不到使用

的方法
Range("A100").CopyFromRecordset myRecordSet

命令将数据水平插入工作表中。该命令将垂直插入数据......: - \

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我认为你需要做一个CopyFromRecordSet然后复制并粘贴转置。看看这个问题:

Transposing CopyFromRecordset Excel VBA

答案 1 :(得分:1)

尝试以下方法:

Dim oRst as ADODB.Recordset
Dim vArray As Variant
Dim oRange As Range

oRst = Rst_From_Access(sSQL_Select) 'Some function that gets whatever recordset
ReDim vArray(1 To oRst.RecordCount, 1 To oRst.RecordCount)
vArray = oRst.GetRows 'Load recordset into an array
vArray = Array2DTranspose(vArray) 'Transpose the array
Set oRange = oBook.Sheets(1).Range(Cells(1, 1), Cells(UBound(vArray, 1), UBound(vArray, 2))) 'Wherever you want to paste the array. 
oRange = vArray 'Paste the array

从以下网址检索到函数Array2DTranspose
http://www.visualbasic.happycodings.com/Applications-VBA/code30.html

Function Array2DTranspose(avValues As Variant) As Variant
Dim lThisCol As Long, lThisRow As Long
Dim lUb2 As Long, lLb2 As Long
Dim lUb1 As Long, lLb1 As Long
Dim avTransposed As Variant

If IsArray(avValues) Then
    On Error GoTo ErrFailed
    lUb2 = UBound(avValues, 2)
    lLb2 = LBound(avValues, 2)
    lUb1 = UBound(avValues, 1)
    lLb1 = LBound(avValues, 1)

    ReDim avTransposed(lLb2 To lUb2, lLb1 To lUb1)
    For lThisCol = lLb1 To lUb1
        For lThisRow = lLb2 To lUb2
            avTransposed(lThisRow, lThisCol) = avValues(lThisCol, lThisRow)
        Next
    Next
End If

Array2DTranspose = avTransposed
Exit Function

ErrFailed:
Debug.Print Err.Description
Debug.Assert False
Array2DTranspose = Empty
Exit Function
Resume
End Function