首页 文章

Excel宏将格式应用于所选范围的倒数第二行

提问于
浏览
0

我正在使用宏来为选定的单元格区域添加格式 . (Excel 2007)所选范围的列数和行数始终不同 . 所选区域也不总是在同一工作表上 .

我记录了一个宏并对代码做了一些小改动,但是我无法弄清楚如何将格式应用于所选范围的倒数第二行的单元格,在这种情况下,这将是双下划线边框 .

Sub feladat()

Application.ScreenUpdating = False

Application.CutCopyMode = False
With Selection
    .HorizontalAlignment = xlCenter
End With

Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .Weight = xlMedium
End With
With Selection.Borders(xlEdgeTop)
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
    .Weight = xlMedium
End With
With Selection.Borders(xlEdgeRight)
    .Weight = xlMedium
End With
With Selection.Borders(xlInsideVertical)
    .Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
    .Weight = xlThin
End With

Selection.SpecialCells(xlCellTypeFormulas, 23).Select
Selection.Font.Bold = True

Application.ScreenUpdating = True

End Sub

我已经尝试使用偏移找到倒数第二行,但没有运气,因为在运行宏之后,活动单元总是位于不同的位置 .

2 回答

  • 0

    首先,只是一些建议:如果你真的需要在选择上应用你的格式,它就可以使用 .Select . 但是你应该首先学习VBA:为了编写一个好的和有效的代码,要避免选择和激活 .

    无论如何要获得所选范围内倒数第二行的选择,您可以使用一对简单的命令:

    TheRow = Selection.Rows.Count-1 + Selection(1).Row
    With Workbooks("NameOfYourWorkbook").Worksheets("NameOfYourWorksheet").Rows(TheRow)
        ' Your formatting here WITHOUT writing Selection
        ' For example: .Borders(xlDiagonalDown).LineStyle = xlNone
    End With
    

    这将获得您选择的行数并减去1.然后添加第一个单元格的行,以便获得清晰的绝对行地址 .
    完成后,您可以应用格式 . 这也不需要新的选择 .

  • 0

    试试这个以查找并应用格式到倒数第二行在运行宏之前选择范围 . 编辑

    Sub NewMacro()
    ShtNm = ActiveSheet.Name
    Var = Split(Selection.Address, "$")
     Rwcnt = Var(UBound(Var))
     NewRng = Var(1) & (Rwcnt-1) & ":" & Var(3) & (Rwcnt-1)
    Sheets(ShtNm).Range(NewRng).Select 
    Call feladat 'Call your function
    End Sub
    

相关问题