在Excel中转​​置SQL结果

时间:2016-05-17 17:55:35

标签: sql excel excel-vba vba

我在VBA工作以自动化报告。当我运行宏时,我会看到数字,但数字会垂直向下插入表单,而不是像我需要的那样横向跨越。这是我到目前为止的代码(包括转换它的代码不起作用)。我该怎么做才能解决它转置?

FromDatex = Range("W39").Value
ToDatex = Range("X39").Value

Range("S7:AD9").ClearContents

        SQLStr = "SELECT SUM(VAL) FROM OPSAHISTM " & _
         "WHERE trunc(DATED) >=to_date('" & FromDatex & "','mm/dd/yyyy') " & _
         "AND trunc(DATED) <=to_date('" & ToDatex & "','mm/dd/yyyy') " & _
         "AND CUSTOMER = '03BA17'" & _
         "GROUP BY TRUNC(DATED,'MM') ORDER BY TRUNC(DATED,'MM')"


rs.Open SQLStr, Cn, adOpenStatic

With Range("S9:AD9")
    .ClearContents
    .CopyFromRecordset rs
    Application.WorksheetFunction.Transpose ("S9:S11")


End With
rs.Close


    Cn.Close
Set rs = Nothing
Set Cn = Nothing

1 个答案:

答案 0 :(得分:0)

你可以这两种方式:

选项1:使用PasteSpecial&gt;&gt; Transpose(与worksheetfunction.transpose不同...真的不确定该公式是做什么的)

Range("S9:S11").Copy
Range("S8").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=True

这将从S9:S11复制并粘贴到S8:U8

选项2::遍历记录集并水平粘贴。而不是使用range.copyFromRecordset,而是在循环记录集中的每条记录时手动从记录集的字段对象中复制值:

Dim writeCol as integer 'the column we are going to write to
writeCol = 19 'Starting at column S

'loop through the Recordset stopping at the last record
Do until rs.EOF
    'Drop into row 9, column writeCol, the value in the first field of your recordset for this record
    Sheet1.Cells(9, writecol).value = rs.Fields(1).value

    'Go to the next record in your record set
    rs.MoveNext
Loop

就个人而言,我喜欢第二个选项,因为它可以让您获得更多控制权,而且您不依赖于剪贴板。返回多少结果并不重要,它只会将它们放在列中,直到它到达记录集的末尾。这个选项的唯一缺点是,如果你有很多记录返回它会慢一些,但是,我打赌如果你有很多记录返回,你可能不希望将它们粘贴到列中。