2016-05-17 83 views
0

我正在使用VBA来自动执行报表。当我运行这个宏时,我得到了数字,但是这些数字自身垂直向下插入,并且不像我需要的那样横向插入。这里是我迄今为止的代码(包括代码转置它不工作)。我能做些什么来解决它转置?将Excel中的SQL结果转换为

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 
+0

rs是什么意思? –

+0

这就是我所说的;这是你的意思?:Set rs = New ADODB.Recordset – lucky123

+0

请改善一个问题。不要忘记添加'Cn'的定义。 –

回答

0

你可以这样做两种方式:

选项1:使用PasteSpecial的移调>>(这是比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 

就个人而言,我喜欢第二个选项,因为它给你更多的控制,你是不是靠在剪贴板上。无论返回多少结果都无关紧要,它只会将它们放在列中,直到它结束记录集。这个选项唯一的缺点是,如果你有很多记录返回,它会变慢,但是我敢打赌,如果你有很多记录返回,你可能不想将它们粘贴到列中。