vba - 转置 CopyFromRecordset Excel VBA

标签 vba excel

我的 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/

相关文章:

java - 获取错误为 "org.apache.poi.hssf.usermodel.HSSFRow cannot be cast to org.apache.poi.ss.usermodel.Row"

c# - 代码运行时退出 Interop 控制的 Excel

ms-access - MS Access DLOOKUP 与文本和嵌套 DLOOKUP 的条件

vba - 使用以编程方式添加的宏从工作表写入另一个工作表

excel - 将变量设置为工作表的代号,在代码中使用它不起作用

excel - 在 VBA Excel 2010 中选择事件行和第一行

vba - Excel/VBA : Is there a shape property I can set to prevent the shape from printing?

vba - 使用 VBA Vlookup 在两个工作表之间工作并填充整列

ms-access - Access VBA 查找最后一次出现的字符串?

html - 将 Excel 工作表中的上标和斜体替换为 HTML 标记