2017-08-14 57 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