Excel Inelegant代码,帮助优化所需

时间:2017-04-23 09:34:09

标签: excel vba excel-vba optimization

我有一些功能完善的代码,但对我来说似乎非常臃肿。如何简化此代码?

Sub RowDiv1()

Dim R1 As Range
Dim R2 As Range
Dim R3 As Range
Dim R4 As Range
Dim R5 As Range
Dim R6 As Range
Dim R7 As Range
Dim R8 As Range

    With Worksheets("Working Sheet 1")
        Set R1 = .Range(.Range("G6000").End(xlUp), .Range("AH6000").End(xlUp))
        With R1
            .Cells(1).Offset(1, -4).Resize(.Rows.Count, .Columns.Count) = .Value
            .ClearContents
        End With

        Set R2 = .Range(.Range("G6000").End(xlUp), .Range("AD6000").End(xlUp))
        With R2
            .Cells(1).Offset(1, -4).Resize(.Rows.Count, .Columns.Count) = .Value
            .ClearContents
        End With

        Set R3 = .Range(.Range("G6000").End(xlUp), .Range("Z6000").End(xlUp))
        With R3
            .Cells(1).Offset(1, -4).Resize(.Rows.Count, .Columns.Count) = .Value
            .ClearContents
        End With

        Set R4 = .Range(.Range("G6000").End(xlUp), .Range("V6000").End(xlUp))
        With R4
            .Cells(1).Offset(1, -4).Resize(.Rows.Count, .Columns.Count) = .Value
            .ClearContents
        End With

        Set R5 = .Range(.Range("G6000").End(xlUp), .Range("R6000").End(xlUp))
        With R5
            .Cells(1).Offset(1, -4).Resize(.Rows.Count, .Columns.Count) = .Value
            .ClearContents
        End With

        Set R6 = .Range(.Range("G6000").End(xlUp), .Range("N6000").End(xlUp))
        With R6
            .Cells(1).Offset(1, -4).Resize(.Rows.Count, .Columns.Count) = .Value
            .ClearContents
        End With

        Set R7 = .Range(.Range("G6000").End(xlUp), .Range("J6000").End(xlUp))
        With R7
            .Cells(1).Offset(1, -4).Resize(.Rows.Count, .Columns.Count) = .Value
            .ClearContents
        End With

    End With


End Sub

正如我所说的,这段代码运行良好,但对于我想要实现的目标,这似乎很长。

2 个答案:

答案 0 :(得分:0)

如果您只是将最后一行分成4列,那么这应该是相同的:

{{1}}

答案 1 :(得分:0)

通过不宣布如此众多的Ranges,您可以实现更高的优雅,只需要为您分配不同的细胞集合,一个接一个。

至于你的其余代码,它更像是一个难题而不是编码任务。当任务是用代码表达思想时,你就会知道这个想法。在一个谜题中,你试图从描述中确定思想,你已经描述过想要改进。这个网站是关于编码。我们不做谜题。