accessjack
Programmer
I mirrored my code of a similar post which did not seem to work for me. thread705-1375620.
I have a table <tblPercent> which hold department, and product, and percent data across region. Here is some sample data.
Department Product North South East West
1 A 25 25 25 25
1 B 10 50 10 30
2 A 50 50 0 0
I need to convert this data using vba to another table in a different format. I know this can be done easily using pivot table in excel, but I am trying to automate this step.
My new table <tblNew> should have output which looks like this:
Department Product Region Percent
1 A North 25
1 A South 25
1 A East 25
1 A West 25
1 B North 10
1 B South 50
1 B East 10
1 B West 30
2 A North 50
2 A South 50
...
Here's my vba code now:
Function MyData()
Dim rs As DAO.Recordset
Dim x As Integer
Dim sql As String
Set rs = CurrentDb.OpenRecordset("tblPercent")
If rs.EOF And rs.BOF Then
Exit Function
End If
Do Until rs.EOF
For x = 3 To 6
sql = "INSERT INTO tblNew(Department, Product, Region, Percent)" & _
"VALUES(" & rs(0) & "," & rs(1) & ",'" & rs(x).Name & _
"','" & rs(x) & "');"
DoCmd.RunSQL sql
Next x
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
End Function
The code compile fine, but when I execute the vba it seems like something is happening, but the tblNew doesn't get created. I'm not sure if I need to reference it somehow in the code or 1st create the table. I've tried creating it but it did not work. Any suggestions on how to get this to work would be greatly appreciated.
Thanks, AccessJack
I have a table <tblPercent> which hold department, and product, and percent data across region. Here is some sample data.
Department Product North South East West
1 A 25 25 25 25
1 B 10 50 10 30
2 A 50 50 0 0
I need to convert this data using vba to another table in a different format. I know this can be done easily using pivot table in excel, but I am trying to automate this step.
My new table <tblNew> should have output which looks like this:
Department Product Region Percent
1 A North 25
1 A South 25
1 A East 25
1 A West 25
1 B North 10
1 B South 50
1 B East 10
1 B West 30
2 A North 50
2 A South 50
...
Here's my vba code now:
Function MyData()
Dim rs As DAO.Recordset
Dim x As Integer
Dim sql As String
Set rs = CurrentDb.OpenRecordset("tblPercent")
If rs.EOF And rs.BOF Then
Exit Function
End If
Do Until rs.EOF
For x = 3 To 6
sql = "INSERT INTO tblNew(Department, Product, Region, Percent)" & _
"VALUES(" & rs(0) & "," & rs(1) & ",'" & rs(x).Name & _
"','" & rs(x) & "');"
DoCmd.RunSQL sql
Next x
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
End Function
The code compile fine, but when I execute the vba it seems like something is happening, but the tblNew doesn't get created. I'm not sure if I need to reference it somehow in the code or 1st create the table. I've tried creating it but it did not work. Any suggestions on how to get this to work would be greatly appreciated.
Thanks, AccessJack