如何从最后一列复制列N次?

问题描述 投票:0回答:1

我目前有以下代码,这是由一位可爱的成员在这里制作的

Sub YearsNumberReduction()
Dim LastCol As Long
Dim DelCnt As Integer
DelCnt = Sheets("Panel").Range("E19").Value
With ThisWorkbook.Sheets("Current")
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    If LastCol >= DelCnt Then
        .Range(.Cells(1, LastCol - DelCnt + 1), .Cells(1, LastCol)).EntireColumn.Delete
    End If
End With

此代码采用最后一列,并按E19中指定的次数删除该列。如何更改代码,因此我们可以添加列而不是从最后一行删除指定的次数?基本上扭转了VBA宏的作用。

我还有另一个问题。在我的Excel解决方案中,我不断添加年数并减少它们(这些年份是业务年度,每年都有利润,按收入成本计算)。在主要工作表上,我有10年。这是默认的年数。但是,当我根据我提到的功能添加或减少年份时,这不会改变。 10年的利润按= SUM计算(B29:B39)。如何更改范围(例如,如果我再添加一年,将在主电子表格中添加11年和= SUM(B29:40),以获得利润概览?

当前添加列

Worksheets("Sheet1").Range("L1:L15").AutoFill Destination:=Worksheets("Sheet1").Range("L1").Resize(15, Worksheets("Panel").Range("E17") + 1), Type:=xlFillDefault

但是,这是从固定列添加而不是最后一列。所以我将列扩展5,它将增加5,但如果我再次将它扩展5,它将不会延伸,因为它有一个固定点。所以我需要根据最后一栏进行更改。

编辑

Year 1  Year 2  Year 3  Year 3  Year 3
Sales   100 115 132 132 152
Costs   30  32  33  33  35
Profit  70  84  99  99  99

3年级保持不变,成本不更新(= C3 * 1.05)它应该上升5%

enter image description here

enter image description here

enter image description here

excel vba excel-vba
1个回答
0
投票

请尝试以下方法。假设您可以使用A列查找上次使用的行:

Sub YearsNumberReduction()

    Dim LastCol As Long
    Dim DelCnt As Integer
    DelCnt = Sheets("Panel").Range("E19").Value
    Dim copyCol As Range
    Dim DestRange As Range
    Dim lastRow As Long

    With ThisWorkbook.Sheets("Current")

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

        Set copyCol = .Range(.Cells(1, LastCol), .Cells(lastRow, LastCol))

        Set DestRange = .Range(.Cells(1, LastCol), .Cells(lastRow, LastCol + DelCnt))

        copyCol.AutoFill Destination:= DestRange, Type:=xlFillDefault

    End With


End Sub
© www.soinside.com 2019 - 2024. All rights reserved.