2016-09-15 34 views
0

我有一個數據集,其中包含許多列,其中包含標題中的標籤和不同長度的值集合。我想插入對應於每個值範圍的標籤到後續的新列中。VBA在每列之後插入帶有絕對引用的空列

我的輸入數據集:

A  B  C 
cat dog fox 
red black yellow ....... 
red white yellow ....... 
grey black yellow ....... 
.......................................... 

我的輸出必須是這樣的:

A B  C  D  E  F ....... 
red cat black dog yellow fox ....... 
red cat white dog yellow fox ....... 
grey cat black dog yellow fox ....... 
.......................................... 

在第一步驟中,我使用的宏每列後插入空白欄:

Public Sub Insert_Blank_Column() 

Dim wks As Worksheet 
Dim iCol As Long 

For Each wks In ActiveWindow.SelectedSheets 

    With wks 
     For iCol _ 
     = .Cells.SpecialCells(xlCellTypeLastCell).column To 1 Step -1 
     .Columns(iCol).Insert 
     Next iCol 
    End With 

Next wks 

End Sub 

但是,我不確定如何使每個新列的「相對」絕對引用。

回答

1
Public Sub Insert_Columns() 

    Dim wks As Worksheet 
    Dim iCol As Long 

    For Each wks In ActiveWindow.SelectedSheets 

     With wks 

      For iCol = .Cells(1, Columns.Count).End(xlToLeft).Column To 1 Step -1 

       'Add a column to the right of each column. 
       .Cells(1, iCol + 1).EntireColumn.Insert 

       'Fill the new column with the value from the first row of the column to its left. 
       Range(.Cells(2, iCol + 1), .Cells(.Cells(1, iCol).End(xlDown).Row, iCol + 1)) = .Cells(1, iCol) 

      Next iCol 

      'Delete the first row. 
      .Cells(1, 1).EntireRow.Delete 

     End With 

    Next wks 

End Sub 
+0

非常感謝!它工作完美。 – In777