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



我使用宏将格式添加到选定的单元格范围。(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

我尝试使用偏移量找到倒数第二行,但没有运气,因为运行宏后活动单元格总是位于不同的地方。

首先,只是一些建议:如果你真的需要在选区上应用你的格式,可以使用.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。然后添加第一个单元格的行,这样就得到了一个明确的绝对行地址。
完成后,您可以应用您的格式。这也不需要新建选区

尝试查找倒数第二行并应用格式在运行宏之前,请选择范围。编辑

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

最新更新