不确定这是否只能在VBA中完成,但如果我能在SQL语句中完全执行此操作,那将是一项很好的技能。
假设我有两个表,第一个如下,一个列直到12(我不认为它设计得很好)
表1
项目ID Month1 Dollars1 Month2 Dollars2 Month3 Dollars3
和第二个表2
项目ID月数
有没有办法可以遍历表1中每一行的列,并为每个Month和Dollar字段创建一个条目?
我可以看到我如何在excvel-VBA中执行此操作,循环遍历列,然后为每个月份的实例和美元或其他内容添加新内容,但是access-vba对我来说有点神秘,尽管SQL对我来说非常直观,如果有可能我也很想知道!
最佳, 库尔特
答案 0 :(得分:2)
尝试这种方法
INSERT INTO Table2
SELECT ProjectID, Month1, Dollars1 FROM Table1
UNION ALL
SELECT ProjectID, Month2, Dollars2 FROM Table1
UNION ALL
SELECT ProjectID, Month3, Dollars3 FROM Table1
UNION ALL
SELECT ProjectID, Month4, Dollars4 FROM Table1
UNION ALL
SELECT ProjectID, Month5, Dollars5 FROM Table1
UNION ALL
SELECT ProjectID, Month6, Dollars6 FROM Table1
UNION ALL
SELECT ProjectID, Month7, Dollars7 FROM Table1
UNION ALL
SELECT ProjectID, Month8, Dollars8 FROM Table1
UNION ALL
SELECT ProjectID, Month9, Dollars9 FROM Table1
UNION ALL
SELECT ProjectID, Month10, Dollars10 FROM Table1
UNION ALL
SELECT ProjectID, Month11, Dollars11 FROM Table1
UNION ALL
SELECT ProjectID, Month12, Dollars12 FROM Table1
UNION ALL
答案 1 :(得分:1)
使用 DAO ,您可以这样做:
Dim db As DAO.Database, rs As DAO.Recordset
Dim month As Long
Dim dat, amount As Variant
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM Table1")
Do Until rs.EOF
For month = 0 To 11
dat = rs(2 * month + 1)
amount = rs(2 * month + 2)
'TODO: Process dat and amount
Next month
rs.MoveNext
Loop
rs.Close: Set rs = Nothing
db.Close: Set db = Nothing
这里我按号码访问列。第0列是[Project ID]
,列#1 Month1
等。
使用 ADO ,过程非常相似:
Dim rs As ADODB.Recordset
Dim month As Long
Dim dat, amount As Variant
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM tlkpMonth", CurrentProject.Connection
Do Until rs.EOF
For month = 0 To 11
dat = rs(2 * month + 1)
amount = rs(2 * month + 2)
'TODO: Process dat and amount
Next month
rs.MoveNext
Loop
rs.Close: Set rs = Nothing