VBA动态范围

时间:2019-03-14 22:10:14

标签: excel vba

VBA的新手。我想更改一个宏,以便能够处理工作表中包含数据的许多行,而不是硬编码值(46)。

Sub test1calc()
'
' test1calc Macro
'

'
'1 - UNSTRESSED POSTED PRODUCT LEVEL BREAKDOWN SUMMED AT NETTING SET
    Columns("AS:AS").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("AS1").Select
    Selection.Interior.Pattern = xlSolid
    Selection.Interior.PatternColorIndex = 2
    Selection.Interior.Color = 65535
    ActiveCell.FormulaR1C1 = "Unstressed Posted Total"
    Range("AS2").Select
    ActiveCell.FormulaR1C1 = "=SUM(RC[-30]:RC[-1])"
    Range("AS2").Select
    Selection.AutoFill Destination:=Range("AS2:AS46")
    Range("AS2:AS46").Select
    ActiveSheet.Calculate
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
End Sub

1 个答案:

答案 0 :(得分:2)

我假设您要填充左侧已有数据的行,而不是工作表中存在的数百万行。

如果是这样,我相信您的代码可以简化为以下内容:

Sub test1calc()

    '1 - UNSTRESSED POSTED PRODUCT LEVEL BREAKDOWN SUMMED AT NETTING SET

    Columns("AS:AS").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

    With Range("AS1")
        .Interior.Pattern = xlSolid
        .Interior.PatternColorIndex = 2
        .Interior.Color = 65535
        .Value = "Unstressed Posted Total"
    End With

    With Range("AS2:AS" & Range("O" & Rows.Count).End(xlUp).Row)
         .FormulaR1C1 = "=SUM(RC[-30]:RC[-1])"
         .Value = .Value
    End With

End Sub