Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Excel中动态插入列?_Excel_Vba - Fatal编程技术网

如何在Excel中动态插入列?

如何在Excel中动态插入列?,excel,vba,Excel,Vba,我想在Excel报告中插入分隔列,以使现有列更易于查看 报告是动态创建的,我不知道会有多少列;可能有5、10、17等 该部分从F开始,转到ival=Application.WorksheetFunction.CountIf(范围(“D2:D”和LastRow)、“其他”) 因此,如果ival=10那么这些列就是fghiklmno,我需要在fg、G&H、H&I、I&J之间插入列。。。和N&O 可以插入列:工作簿(“您的工作簿”)。工作表(“工作表”)。列(i)。插入 但我不知道如何循环通过ival

我想在Excel报告中插入分隔列,以使现有列更易于查看

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

该部分从F开始,转到
ival=Application.WorksheetFunction.CountIf(范围(“D2:D”和LastRow)、“其他”)

因此,如果
ival=10
那么这些列就是fghiklmno,我需要在fg、G&H、H&I、I&J之间插入列。。。和N&O

可以插入列:
工作簿(“您的工作簿”)。工作表(“工作表”)。列(i)。插入

但我不知道如何循环通过
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
试试这个:

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

下面的代码应该可以正常工作,而无需担心
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