首页 > 解决方案 > 如何在具有特定标题的每列之后插入 3 列?

问题描述

我有一个 Excel 表,其中第一列标题是“项目编号”,第二列标题(B 列)是“365 天销售”,接下来的 1-50 列标题是“Next_Item_X”,其中 X 是数字 1-50。

我想在每个“Next_Item_X”列之后插入 3 列,标题为“365_Day_Sales_X”、“Total_On_Hand_X”和“Open_PO_QTY_X”,其中 X 与插入的列标题中的 X 相同。

非常感谢你,

标签: excelvba

解决方案


由于我没有收到对此的答案,或者我的最后一个问题因为没有集中注意力而被阻止,我将分享我想出的解决方法。

选择我要运行代码的最后一列后,此代码将在所选列之后插入 3 列带有列标题的列。它会按照我用输入框告诉它的次数执行此操作,向后移动(例如 E 列到 A 列)。它还将公式插入到每个添加列的第二行,并将公式自动填充到最后一行。

我试图找出是否有人可以在不需要输入框的情况下做到这一点,但这工作得很好,我对结果非常满意:

Sub 365_Insert_Columns()

LastRow = ActiveWorkbook.ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row

MsgBox "Select last column to insert after before running macro."

I2 = Selection.Column + 1

I3 = InputBox("Enter number of columns to insert", "Insert Columns")
If I3 = vbNullString Then
    MsgBox "Macro Cancelled."
    Exit Sub
End If

For I = 0 To I3 - 1

S = Right(Cells(1, (I2 - 1) - I).Value, Len(Cells(1, Selection.Column).Value) - 5)
rngS = Replace(Cells(2, (I2 - 1) - I).Address, "$", "")

Columns(I2 - I).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(1, I2 - I).Value = "365_Day_Sales_" & S
Cells(2, I2 - I).Value = "=IFERROR(VLOOKUP(" & rngS & ",'365_Sales_Pivot'!A:B,2,0), 0)"
Cells(2, I2 - I).AutoFill Destination:=Range(Cells(2, I2 - I), Cells(LastRow, I2 - I))
Columns(I2 - I).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(1, I2 - I).Value = "On_Hand_" & S
Cells(2, I2 - I).Value = "=IFERROR(VLOOKUP(" & rngS & ",'Total_On_Hand'!A:B,2,0), 0)"
Cells(2, I2 - I).AutoFill Destination:=Range(Cells(2, I2 - I), Cells(LastRow, I2 - I))
Columns(I2 - I).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(1, I2 - I).Value = "Open_PO_QTY_" & S
Cells(2, I2 - I).Value = "=IFERROR(VLOOKUP(" & rngS & ",'Open_PO_QTY'!A:B,2,0), 0)"
Cells(2, I2 - I).AutoFill Destination:=Range(Cells(2, I2 - I), Cells(LastRow, I2 - I))

Next I

Call AutoBorders
Call AutoFitCells

End Sub

推荐阅读