2012-08-02 12 views
0

我真的一直在尋找答案,仍然無法找到答案。請幫忙!在SQL中分別將列轉換爲行

我在Excel中有一個工作簿,我想在使用VBA或SQL的Access中進行操作。

我面臨的當前問題是我有一個電子表格,其中每行是基於一張發票(2500行)。每一行由「發票號碼」「採購訂單編號」「發票日期」「發票合計」組成。我們可以稱之爲發票數據

然後在該行中有基於行項目信息「物料編號」「物料成本」「物料數量」的單元格。行項目數據

,而項目中的數據重複,直到從覆蓋的發票各行項目(即如果70線項目,將有70個不同的行項目數據和列的bunchhhhh)

我需要一種方法使每行都基於行項目信息而不是發票信息,而每行仍然保留項目各自的發票信息(「發票號」「採購訂單號」「發票日期」「發票總計」)。

此外,代碼必須足夠簡單,我不需要告訴它複製第1行項目數據,第2行項目數據等,直到行項目70數據爲止。 (也許它可以理解每3列是一個新的項目,它所在的行有它的發票信息)。它也不能停止,當行1上有空列時,因爲第30行中可能有50個項目(發票1有3個行項目,發票30有50個行項目)

我會繼續尋找找到一個答案,如果我找到一個我會在這裏發佈..感謝您的幫助提前!

+0

我看不到一個簡單的方法來做到這一點,除非每個項目明細集還包含一個發票號碼,並且您指出它沒有。如果一次性轉移,這將更容易。 – Fionnuala 2012-08-02 20:26:46

回答

1
Sub UnPivot() 

Const INV_COLS As Integer = 4 'how many columns in the invoice info 
Const ITEM_COLS As Integer = 3 'columns in each set of line item info 

Dim shtIn As Worksheet, shtOut As Worksheet 
Dim c As Range 
Dim rOut As Long, col As Long 


    Set shtIn = ThisWorkbook.Sheets("Data") 
    Set shtOut = ThisWorkbook.Sheets("Output") 

    Set c = shtIn.Range("A2") 'first cell in invoice info 
    rOut = 2     'start row on output sheet 

    'while the invoice cell is non-blank... 
    Do While Len(c.Value) > 0 
     col = INV_COLS + 1 'column for first line item 
     'while there's info in the line item cell 
     Do While Application.CountA(shtIn.Cells(c.Row, col).Resize(1, ITEM_COLS)) > 0 

      'copy the invoice info (four cells) 
      c.Resize(1, INV_COLS).Copy shtOut.Cells(rOut, 1) 

      'copy the line item info (3 cells) 
      shtIn.Cells(c.Row, col).Resize(1, ITEM_COLS).Copy _ 
          shtOut.Cells(rOut, INV_COLS + 1) 

      rOut = rOut + 1   'next output row 
      col = col + ITEM_COLS  'move over to next line item 
     Loop 
     Set c = c.Offset(1, 0) 'move down one cell on input sheet 
    Loop 

    shtOut.Activate 
End Sub 
+0

查看我的評論 – 2012-08-02 21:19:07

+0

我得到運行時錯誤9下標超出範圍,再次感謝 – user1572395 2012-08-02 21:27:43

+0

在哪一行?在包含宏的Excel工作簿中是否有名爲「數據」和「輸出」的工作表? – 2012-08-03 01:09:05