首页 文章

VBA Excel复制并插入具有值和格式的不同行数

提问于
浏览
0

我正在尝试编写一个适用于各种工作表的宏 . 这些都是按月更新的 . 在这些工作表中,我们在工作表顶部有30到100行,其中包含有关当前月份的公式 . 下面我们有所有前几个月的数字,但没有公式 .

每个月我们都会复制最上面的行集并将它们作为值插入具有公式的行下方的相同格式,以便我们可以再次开始月份,但记录上个月的数字 .

总之,我需要从行(X 1)开始复制和插入所有列和(X行数),仅作为值和格式 . 行(X 1)也不是表格的末尾 .

我在下面的代码中有一些开头,但第一列确实包含空值 .

Sub MonthlyReset()

    Dim TotalImpacts As Worksheet
    Dim LastImpacts As Range
    Dim Counter As String


   Set TotalImpacts = Worksheets("Total Impacts")

Counter = Application.WorksheetFunction.Match("STOP", ThisWorkbook.Sheets(TotalImpacts).Column(1), 0)

LastImpacts = ThisWorkbook.Sheets(TotalImpacts).Rows("1:" & Counter)
Rows(Counter).Resize(Counter).Insert

'Copying Impacts
ThisWorkbook.Sheets(TotalImpacts).LastImpacts.Copy
'Paste Values then Formatting
ThisWorkbook.Sheets(TotalImpacts).Range("A" & Counter + 1).PasteSpecial Paste:=xlPasteValues
ThisWorkbook.Sheets(TotalImpacts).Range("A" & Counter + 1).PasteSpecial Paste:=xlPasteFormats
'Clear Clipboard
Application.CutCopyMode = False


End Sub

1 回答

  • 0

    这不是最有效的方法,但插入整行可能是一个很好的痛苦,有趣的是 . 但是为了忠实于你原来的想法,这应该有效 .

    Sub MonthlyReset()
    
    Dim TotalImpacts As Worksheet
    Dim LastImpacts As Range
    Dim Counter As String
    
    
    'Set the worksheet we are working with
    Set TotalImpacts = Worksheets("Total Impacts")
    
    'Find the row that STOP is on
    Counter = Application.WorksheetFunction.Match("STOP", TotalImpacts.Columns(1), 0)
    
    'Set the range for the data we want to copy
    Set LastImpacts = TotalImpacts.Rows("1:" & Counter)
    
    'Copy and insert
    LastImpacts.Copy
    LastImpacts.Offset(Counter).Insert shift:=xlShiftDown
    
    'Paste Values then Formatting
    TotalImpacts.Range("A" & Counter + 1).PasteSpecial Paste:=xlPasteValues
    TotalImpacts.Range("A" & Counter + 1).PasteSpecial Paste:=xlPasteFormats
    
    'Clear Clipboard
    Application.CutCopyMode = False
    
    
    End Sub
    

    最后,该范围被粘贴两次,第一次使用公式来插入正确数量的行 . 第二次是粘贴值,然后单独粘贴公式,就像在原始代码中一样 .

相关问题