我怎样才能从Access数据库读取多列?
我已经分配了任务来计算来自Access的一些值并将它们存储到Excel中。 我的代码工作,如果我使用单列数据库。
我的代码如下所示:
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
更新:
我的程序有1列这样的: https : //prntscr.com/a90g5z
我的程序有2列这样的: https : //prntscr.com/a90gpi
我的数据库访问是这样的: https : //prntscr.com/a90h0q
假设Recordset
只有一条logging,那么你应该纠正你的代码,如下面的代码片段所示:
TextBox1.Value = Recordset.Fields(0).Value TextBox2.Value = Recordset.Fields(1).Value
等等(如果你有两个以上的字段)。 显然,你不需要For
循环来完成这个任务。
我已经使用这种方法将Access中的数据导入到Excel中:
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
'如果你想要前3列只用单元格(nb_rows,3)replace单元格(nb_rows,nb_cols)
使用此代码来replace“for col = 0到Recordset.Fields.Count – 1 …. next”