插入列dynamicvba
我有一个报告的一部分是很难阅读,我想插入分离列,使其更容易查看。
该报告是dynamic创build的,我不知道有多less列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
之间插入列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
尝试下面的代码:
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
尝试这个:
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