在某个heade之前插入一个新列

时间:2016-05-31 13:33:25

标签: excel vba

使用Excel VBA,我希望有一个按钮,可以添加一个新功能#' ' Total'之前的专栏列,每次按下按钮。

基本上,一个按钮执行以下操作,从图像1 - > 2 - > 3.

1 enter image description here

2 enter image description here

第3 enter image description here

更新 enter image description here

2 个答案:

答案 0 :(得分:1)

假设数据以A1开头(请参阅下图)

Sub Button1_Click()
    columntoinsert = Cells(1, 1).End(xlToRight).Column
    Columns(columntoinsert).Insert
    Cells(1, columntoinsert) = "Feature" & columntoinsert - 1
End Sub

enter image description here

点击按钮后:

enter image description here

答案 1 :(得分:1)

假设您的表来自Cell A2,请尝试以下操作:

Sub InsertColumn()
    Dim lastColumn As Long, lastRow As Long

    lastColumn = Cells(2, Columns.Count).End(xlToLeft).Column
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row

    Columns(lastColumn - 1).Select
    Range(Selection, Selection).Select
    Selection.Copy
    Selection.Insert Shift:=xlToRight
    Application.CutCopyMode = False

    Cells(2, lastColumn).Value = "Feature" & " " & lastColumn - 1
    Range(Cells(3, lastColumn), Cells(lastRow, lastColumn)).ClearContents
    Cells(1, 1).Select
End Sub

修改: 的 _________________________________________________________________________________

此代码适用于更新的问题或添加的图像。

Sub InsertColumn111()
    Dim lastColumn As Long, lastRow As Long
    Dim rConstants As Range

    lastColumn = Cells(2, Columns.Count).End(xlToLeft).Column
    lastRow = Range("A1").End(xlDown).Row

    Columns(lastColumn - 1).Select
    Selection.Copy
    Selection.Insert Shift:=xlToRight
    Application.CutCopyMode = False

    Cells(2, lastColumn).Value = "Feature" & " " & lastColumn - 1
    Range(Cells(3, lastColumn), Cells(lastRow, lastColumn)).ClearContents

    lastRow = Cells(Rows.Count, "A").End(xlUp).Row
    Rows(lastRow - 1).Select
    Selection.Copy
    Selection.Insert Shift:=xlToBottom
    Application.CutCopyMode = False

    Cells(lastRow, 1).Value = "Feature" & " " & lastRow - 7
    Set rConstants = Range(Cells(lastRow, 2), Cells(lastRow, lastColumn)).SpecialCells(xlCellTypeConstants)
    rConstants.ClearContents

    Cells(1, 1).Select
End Sub