自动格式化过早结束

时间:2019-05-17 11:59:31

标签: excel vba

如果有条目,我设置了一个宏来格式化电子表格中的行。我使用条目不多的文件进行设置,而当条目较多的文件上使用它时,它会提前停止。

我已经看过代码了,对我而言,为什么它无法正常运行是没有意义的。

Range(Range("A2"), Range("E2").End(xlDown)).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .ColorIndex = xlAutomatic
    .TintAndShade = 0
    .Weight = xlThin
End With

2 个答案:

答案 0 :(得分:0)

这是一个未经测试的示例:

Sub BordersAndFilters()


    Dim ws As Worksheet
    Dim aBorderSettings() As Long           'Calls the array
    Dim i As Long

    Set ws = ThisWorkbook.Worksheets("Data") 'your worksheet name

    ReDim aBorderSettings(1 To 8, 1 To 2)   'An Array of length 8x2 (table)
        aBorderSettings(1, 1) = xlDiagonalDown:     aBorderSettings(1, 2) = xlNone
        aBorderSettings(2, 1) = xlDiagonalUp:       aBorderSettings(2, 2) = xlNone
        aBorderSettings(3, 1) = xlEdgeBottom:       aBorderSettings(3, 2) = xlContinuous
        aBorderSettings(4, 1) = xlEdgeLeft:         aBorderSettings(4, 2) = xlNone
        aBorderSettings(5, 1) = xlEdgeRight:        aBorderSettings(5, 2) = xlNone
        aBorderSettings(6, 1) = xlEdgeTop:          aBorderSettings(6, 2) = xlNone
        aBorderSettings(7, 1) = xlInsideHorizontal: aBorderSettings(7, 2) = xlNone
        aBorderSettings(8, 1) = xlInsideVertical:   aBorderSettings(8, 2) = xlNone

    With ws.Range("A2:E" & ws.Cells(ws.Rows.Count, "E").End(xlUp).Row)  'Instead of using LastRow. The "E" should be your column with guaranteed values in every row.
        'Filter and Fit
        .AutoFilter 'remove this if you don't want to filter
        .EntireColumn.AutoFit 'remove this if you don't want to fit the cells to column width

        'For every number in the array, change the borders based on the values in the array
        For i = LBound(aBorderSettings, 1) To UBound(aBorderSettings, 1)
            .Borders(aBorderSettings(i, 1)).LineStyle = aBorderSettings(i, 2)
            If aBorderSettings(i, 2) <> xlNone Then
                .Borders(aBorderSettings(i, 1)).ColorIndex = xlAutomatic
                .Borders(aBorderSettings(i, 1)).TintAndShade = 0
                .Borders(aBorderSettings(i, 1)).Weight = xlThin
            End If
        Next i

    End With

 End Sub

答案 1 :(得分:0)

根据我的评论,修正代码的最简单方法是像这样修改它;

With Sheets("Sheet1").Range("A2:E" & Cells(Rows.Count, "A").End(xlUp).Row)
    'Identify the worksheet, use xlUp, and remove Select/Selection
    .Borders(xlDiagonalDown).LineStyle = xlNone
    .Borders(xlDiagonalUp).LineStyle = xlNone
    .Borders(xlEdgeLeft).LineStyle = xlNone
    .Borders(xlEdgeTop).LineStyle = xlNone
    With .Borders(xlEdgeBottom) 
        .LineStyle = xlContinuous
        .ColorIndex = xlAutomatic
        .TintAndShade = 0
        .Weight = xlThin
    End With
End With