转置CopyFromRecordset Excel VBA

在Excel VBA中,我有以下代码将SQL表中的数据复制到Excel中。 这个数据是从单元格C2开始水平插入的,但是我希望它被垂直地插入到C列。

Sheets("Control").Range("C2").CopyFromRecorset rsPubs 

其中rsPubs是我的ADO连接。

基本上,我只是想要这个数据转置。 什么是这样做的有效方式? 任何帮助将不胜感激!

编辑:这是如何创buildrsPubs (连接工作正常,因为我实际上得到的数据):

 ' 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 

目前我无法testing,但您可以:

 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 

你也可以使用转置工作表function – 但是,我现在还不完全直接这样做,希望你的input数据已经转换了。

编辑:

这里是一个很好的官方示例和关于此主题的更多信息: http : //support.microsoft.com/kb/246335/en-us

特别是“使用GetRows”部分。

EDIT2:

这应该做的

 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

未经testing:

 Sub CopyTransposed(rng As Range, rs As ADODB.Recordset) Dim x As Long, y As Long x = 0 Do While Not rs.EOF For y = 0 To rs.Fields.Count - 1 rng.Offset(y, x).Value = rs.Fields(y).Value Next y x = x + 1 rs.MoveNext Loop End Sub 

我的build议是不使用VBA。 Microsoft已经为您提供了从数据库导入数据的function。

 Data -> Import External Data 

然后,它将在工作表内创build一个QueryTable,您可以右键单击并定期刷新。 另一个好处是你没有得到令人讨厌的macros观警告。 QueryTable可以是表,查询或存储过程。

尝试一下!

在接受的答案中编辑2不适用于我,但以下(见我的来源http://www.mrexcel.com/forum/excel-questions/513845-copyfromrecordset-transpose.html ):

 Public Sub PlaceTransposedResults(oResults As ADODB.Recordset, rTarget As Range) Dim vTransposed As Variant If Not oResults.EOF Then vTransposed = oResults.GetRows rTarget.Resize(UBound(vTransposed, 1) + 1, UBound(vTransposed, 2) + 1) = vTransposed End If End Sub 

(这假设你没有改变与OPTION BASE的数组基础,并且你的Excel版本有Range.Resize ,并且oResults永远不是什么都没有)

对此进行一个调整就是使其成为一个函数,并返回正确大小的范围 – 如果要调整指定范围以覆盖结果集,则很有用。

另一个可能的调整是你可能希望允许用户要求添加字段名称作为第一列。 我找不到比以下更好的东西:

 Dim ix As Integer For ix = 0 To oResults.Fields.Count - 1 rTarget.Offset(ix, 0) = oResults.Fields(ix).Name Next ix 

(当然,在这种情况下,您必须将主要结果抵消1列)。