2017-08-14 58 views
0

我有一個sql查詢,輸出某些貨幣值。我需要將該表格提取到我的excel工作表中,然後將貨幣除以1.在我的情況下,只有第一種貨幣被當前檢索,然後其餘貨幣僅複製與第一種貨幣相同的值。我應該採用不同的方法嗎?將SQL表結果除以1 - 循環通過recorset

 Dim rst As ADODB.Recordset 
     Set rst = conn.Execute("SELECT [midpoint] " _ 
        & "FROM[FOREX] " _ 
        & "Where currency in ('CAD','AUD','EURO','HKD','JPY','MYR','NZD','SGD','THB') and " _ 
        & "xdate=(select max(xdate) FROM [FOREX] where currency in ('CAD','AUD','EURO','HKD','JPY','MYR','NZD','SGD','THB'))") 
    If rst.EOF Then 
     Exit Sub 
    End If 

    Dim rstCAD As Double 

    Sheets("Tables").Range("FX2USD_CAD").Value = 1/rst(0) 
    Sheets("Tables").Range("FX2USD_AUD").Value = 1/rst(1) 
    Sheets("Tables").Range("FX2USD_EURO").Value = 1/rst(2) 
    Sheets("Tables").Range("FX2USD_HKD").Value = 1/rst(3) 
    Sheets("Tables").Range("FX2USD_JPY").Value = 1/rst(4)  
    Sheets("Tables").Range("FX2USD_MYR").Value = 1/rst(5) 
    Sheets("Tables").Range("FX2USD_NZD").Value = 1/rst(6) 
    Sheets("Tables").Range("FX2USD_SGD").Value = 1/rst(7) 
    Sheets("Tables").Range("FX2USD_THB").Value = 1/rst(8) 
    Sheets("Tables").Range("FXLastUpdated").Value = Now 

End If 
+1

我缺少的東西?你除以一個?這在數學上與您的值(x/1 = x)相同。你的意思是你正在考慮貨幣的逆轉嗎?即1/X? – SandPiper

回答

1

rst(1)嘗試讀取第一行的第二,但你只有一列。

需要調用.movenext移動到下一行,你可以循環,但你有值的預定順序,這樣,而不是你可以:

dim sht as worksheet: set sht = Sheets("Tables") 

with sht 
    .Range("FX2USD_CAD").Value = 1/rst(0) 
    rst.movenext 

    .Range("FX2USD_AUD").Value = 1/rst(0) 
    rst.movenext 

    ... and so on 
end with 

您需要修改SQL &添加ORDER BY條款以確保查詢結果中行的順序與代碼中的FX2USD_CAD_*的順序匹配。

0

,必須用你的代碼爲while-loop

i = 0 
While Not rs.EOF ' keep cycling untill all rows have been retrived 
    ' write the value of the i-th cell 
    Sheets("Tables").offset(index).Range("FX2USD_CAD").Value = 1/rst(0) 
    ' one line per column (FX2USD_AUD, FX2USD_EURO, ...) 
    rst.MoveNext ' retrive the next row 
    i = i + 1 ' mode the index by one 
Wend 

,當然,閉上你的語句時,你就完蛋了:rst.Close