我试图将第一行的格式复制到我的范围内的其余行

时间:2014-01-08 11:22:05

标签: excel excel-vba vba

我创建了2个func,但都给出了Run-time error '1004': Application-defined or object-defined错误。你能告诉我这里的错误是什么吗?

Sub test()
    Dim RowCount, ColumnCount As Integer
    Dim sRangeSt, sRangeEn, tRangeSt, tRangeEn As String
    Dim tmpRange As Range

        RowCount = Range("main").Rows.Count
        ColumnCount = Range("main").Columns.Count

        'prepare range start and end cell-addresses
        sRangeSt = Range("main").End(xlToLeft).Offset(1, 0).Address
        sRangeEn = Range("main").End(xlToLeft).Offset(1, 0).End(xlToRight).Address
        tRangeSt = Range("main").End(xlToLeft).Offset(2, 0).Address
        tRangeEn = Range("main").End(xlToLeft).Offset(RowCount - 1, ColumnCount - 1).Address

        'Perform style copy
        Range(sRangeSt & ":" & sRangeEn).Copy
        'Worksheets("Report").Select
        Worksheets("Report").Range(tRangeSt & ":" & tRangeEn).PasteSpecial xlPasteFormats
End Sub


Sub test2()
    Dim sRangeSt, sRangeEn, tRangeSt, tRangeEn As String
    sRangeSt = Range("main").End(xlToLeft).Offset(1, 0).Address
    sRangeEn = Range("main").End(xlToLeft).Offset(1, 0).End(xlToRight).Address

    'Perform style copy
    Range(sRangeSt & ":" & sRangeEn).Copy

    For Each Row In Range("main").Rows
        Range(Row.Address).PasteSpecial xmlPasteFormts
    Next Row
End Sub

第一个块在最后一行给出错误。我尝试减少目标行的行数,并且它对于excel范围4096行运行正常,但是对于具有上述错误的更大行数的范围则失败。

1 个答案:

答案 0 :(得分:0)

您收到该错误是因为您的范围不完全合格。只需将代码括在With End With中,就不会限定范围。在每个范围之前添加.(DOT)。例如

With Sheets("Report")
    RowCount = Range("main").Rows.Count
    ColumnCount = Range("main").Columns.Count

变为

With Sheets("Report")
    RowCount = .Range("main").Rows.Count
    ColumnCount = .Range("main").Columns.Count

其他类似