嗨伙计我试图获取数据的值(0)
并把它变成变量InvoiceNumber。我试着把我的手表屏幕的图像,但我最终没有被允许。但这是我的手表屏幕的样子。
数据
数据(0)
数据(0,1)1
数据(0,2)2
数据(0,3)3
我试过了
dim InvoiceNumber as variant <br/>
invoiceNumber = data(0)
但我一直在收到错误。我不知道如何引用该数组的部分。任何帮助将不胜感激。
这里是任何希望看到更多内容的人的完整代码。
Dim db As Database
Dim rs As Recordset
Dim data As Variant
Dim colummn1 As Variant
Dim obj As Object
Set db = CurrentDb
Set rs = db.OpenRecordset("select * from Table1")
'set obj = new object
While Not rs.EOF
'MsgBox (rs.RecordCount)
'MsgBox (rs.Fields.Count)
data = rs.GetRows(rs.Fields.Count)
Column1 = data.data(0)
Wend
rs.Close
db.Close
End Sub
答案 0 :(得分:1)
尝试
Column1 = data(0,0)
而不是
Column1 = data.data(0)
data
包含一个二维数组。第一个索引是字段编号,第二个索引是行编号。两者都从零开始。所以data(0,0)
是第一行的第一个字段。 data(1,0)
是第一行的第二个字段。
我会尝试使用用户定义的类型
制作一组发票Public Type Invoice
Nr As Variant
IssueDate As Variant
Total As Variant
'Or whatever your invoice contains
End Type
Public Sub TestGetRecords()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim data As Variant
Dim numRecords As Long, i As Long
Dim Invoices() As Invoice
Set db = CurrentDb
Set rs = db.OpenRecordset("select * from Table1")
data = rs.GetRows()
rs.Close
db.Close
numRecords = UBound(data, 2) + 1
ReDim Invoices(0 To numRecords - 1) As Invoice
For i = 0 To numRecords - 1
Invoices(i).Nr = data(0, i)
Invoices(i).IssueDate = data(1, i)
Invoices(i).Total = data(2, i)
Next i
Debug.Print Invoices(0).Total
End Sub
解决方案中的错误是,您将GetRows
置于循环中。但是,GetRows会立即返回所有行!
答案 1 :(得分:0)
我发现有点难以理解你想要实现的目标。
您正在将整个数据表读入记录集对象,将记录集对象的字段加载到二维数组中,然后尝试迭代数组以将结果输出到单个变量(或数组的总和)值)。
为什么不直接使用SQL表达式从表中提取数据?
如果我们可以假设您有一张发票表(比如......“myInvoiceTable”),至少包含以下字段......
invoiceID 发票面额 (可能还有很多其他的,例如invoiceDate,clientID等)
你可以写一个像这样的表达式
“SELECT SUM(invoiceValue)AS MyTotal FROM myInvoiceTable WHERE invoiceID&gt; xxxx”
这可能会像这样进入您的VBA代码。
Dim rst as Recordset
Dim strSQL as string
strSQL = "SELECT SUM(invoiceValue) AS MyTotal FROM myInvoiceTable WHERE invoiceID > 400" '-- use an appropriate WHERE clause if needed
Set rst = CurrentDb.Openrecordset(strSQL) '-- the rst object should contain a single value "MyTotal" which is the sum of the fields you are trying to access
MsgBox rst!MyTotal '-- use this value wherever you need to use it