如何在Excel中动态插入列?

时间:2013-06-05 01:11:35

标签: excel excel-vba vba

我想将分隔列插入Excel报表,以便更容易查看现有列。

报告是动态创建的,我不知道会有多少列;可能有5,10,17等。

该部分从F开始,然后转到ival=Application.WorksheetFunction.CountIf(range("D2:D" & LastRow), "Other")

因此,如果ival=10那么列是FGHIJKLMNO,我需要在F& G,G& H,H& I,I& J,...和N& O之间插入列。

这可能是插入列的可能性:Workbooks("yourworkbook").Worksheets("theworksheet").Columns(i).Insert

但我不确定如何循环ival

Sub InsertColumns()
    Dim iVal As Integer
    Dim Rng As range
    Dim LastRow As Long
    Dim i  As Integer

    With Sheets("sheet1")
        LastRow = .range("D" & .Rows.Count).End(xlUp).Row
    End With

    iVal = Application.WorksheetFunction.CountIf(range("D2:D" & LastRow), "Other")

    For i = 7 To iVal - 1
    Workbooks("yourworkbook").Worksheets("theworksheet").Columns(i+1).Insert
    Next i

End Sub

2 个答案:

答案 0 :(得分:9)

以下代码应该无需担心ival

Sub InsertSeparatorColumns()

    Dim lastCol As Long

    With Sheets("sheet1")
        lastCol = Cells(2, .Columns.Count).End(xlToLeft).Column

        For i = lastCol To 7 Step -1
            .Columns(i).Insert
            .Columns(i).ColumnWidth = 0.5
        Next

    End With

End Sub

答案 1 :(得分:3)

试试这个:

Sub InsertSeparatorColumns()
    Dim ws as Worksheet
    Dim firstCol As String
    Dim lastRow As Long
    Dim i As Long
    Dim howManySeparators As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")
    firstCol = "F"
    lastRow = ws.Range("D" & ws.Rows.Count).End(xlUp).Row
    howManySeparators = Application.WorksheetFunction.CountIf _
                            (ws.range("D2:D" & LastRow), "Other")

    For i = 1 To howManySeparators * 2 Step 2
        ws.Range(firstCol & 1).Offset(, i).EntireColumn.Insert
    Next i
End Sub