2016-02-28 151 views
1

我被分配到从Access计算一些数值,并将它们存储到Excel任务。如果我使用单列数据库,我的代码可以工作。我如何从Access数据库中读取多个列?

我的代码如下所示:

With Recordset 
     Source = "SELECT tbl_cog.[Latitude] FROM tbl_cog WHERE Company='Bandung Food Truck Festival Members'" 
     .Open Source:=Source, ActiveConnection:=Connection 
     For Col = 0 To Recordset.Fields.Count - 1 
      TextBox1.Value = Recordset.Fields(Col).Value 
     Next 
    End With 

但是,当我想读多列,我的代码只是读一列。我的代码如下所示:

With Recordset 
     Source = "SELECT tbl_cog.[Latitude], tbl_cog.[Longitude] FROM tbl_cog WHERE Company='Bandung Food Truck Festival Members'" 
     .Open Source:=Source, ActiveConnection:=Connection 
     For Col = 0 To Recordset.Fields.Count - 1 
      TextBox1.Value = Recordset.Fields(Col).Value 
      TextBox2.Value = Recordset.Fields(Col).Value 
     Next 
    End With 

UPDATE:

我计划用1这样的柱:https://prntscr.com/a90g5z

我的程序有2列是这样的:https://prntscr.com/a90gpi

我这样的数据库访问:https://prntscr.com/a90h0q

+1

似乎你的循环不会在正确的方向上取向。是否有超过一个记录返回?如果不是,那么为什么不选择'SELECT TOP 1 ...'来确保?如果你想遍历字段而不是记录,那么TextBox的索引应该改变。你拥有它的方式是将field1放入两个文本框中,然后将field2放入两个复选框中。 – Jeeped

回答

2

假设有在Recordset,唯一的一个记录n您应该纠正你的代码一样显示在下面的代码片段:

TextBox1.Value = Recordset.Fields(0).Value 
TextBox2.Value = Recordset.Fields(1).Value 

等等(如果你有两个以上的字段)。显然,你不需要For循环来完成这个任务。

1

我已经使用这个方法从Access将数据到Excel:如果你想第一个3列刚刚替换细胞的细胞(nb_rows,nb_cols)

DataArray = Recordset.GetRows() 'all the data from the Select is transferred to an array 
nb_rows = UBound(DataArray, 1) 'calculate the number of rows of the array 
nb_cols = UBound(DataArray, 2) 'calculate the number of columns of the array 

'paste the array to excel 
Sheets(1).Range(Cells(1, 1), Cells(nb_rows, nb_cols)).Value = DataArray 

”(nb_rows,3)

使用此代码来替换“的山坳= 0至Recordset.Fields.Count - 1 ....下一步”

相关问题