将SQL表结果除以1 – 循环通过recorset

我有一个SQL查询输出某些货币值。 我需要将该表提取到我的Excel工作表,然后将货币除以1.在我的情况下,只有第一个货币获取当前,然后rest只是复制相同的价值作为第一个货币。 我应该采取不同的方法吗?

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 

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_*的顺序相匹配。

你必须把你的代码包装到一个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 

当然,当你完成时closures你的陈述:rst.Close