我的 Excel VBA 中有以下代码,可将 SQL 中的表中的数据复制到 Excel 中。该数据从单元格 C2 开始水平插入,但我希望将其垂直插入到 C 列。
Sheets("Control").Range("C2").CopyFromRecorset rsPubs
其中 rsPubs
是我的 ADO 连接。
基本上,我只想转置这些数据。执行此操作的有效方法是什么?
这就是 rsPubs
的创建方式(连接工作正常,因为我实际上正在获取数据):
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "SELECT * FROM Analytics.dbo.XBodoffFinalAllocation"
' Copy the records into cell B3 on Sheet1.
Sheets("Control").Range("C2").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
最佳答案
我目前无法对此进行测试,但您可以:
Sheets("Control").Range("C2").CopyFromRecorset rsPubs 'copy your data
Sheets("Control").Range("C2").Copy 'copy the data into clipboard
Sheets("Control").Range("C2").PasteSpecial xlPasteValues, xlPasteSpecialOperationNone, True, True
您也可以使用转置工作表函数 - 但是,我现在还没有找到直接执行此操作的方法,预计您的输入数据已经转置。
这是一个很好的官方示例以及有关此主题的更多信息: How to transfer data from an ADO Recordset to Excel with automation
特别是“使用 GetRows”部分。
这应该做:
Dim resultset As Variant
Dim result As Variant
resultset = rsPubs.GetRows
result = Application.WorksheetFunction.Transpose(resultset)
Sheets("Control").Range("C2").Resize(UBound(result, 1), UBound(result, 2)) = result
http://www.teachexcel.com/excel-help/excel-how-to.php?i=147811
关于vba - 转置 CopyFromRecordset Excel VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13141639/