2016-05-17 70 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 

就個人而言,我喜歡第二個選項,因爲它給你更多的控制,你是不是靠在剪貼板上。無論返回多少結果都無關緊要,它只會將它們放在列中,直到它結束記錄集。這個選項唯一的缺點是,如果你有很多記錄返回,它會變慢,但是我敢打賭,如果你有很多記錄返回,你可能不想將它們粘貼到列中。