【问题标题】:VBA & Excel: Selecting the row below a selectionVBA 和 Excel:选择所选内容下方的行
【发布时间】:2021-08-28 00:27:48
【问题描述】:

我知道这个问题可能会被问到很多,但我无法找到或理解我正在寻找的确切答案。

我今天第一次在 excel 中学习 VBA,我正在尝试自动格式化一个值表,并希望它适用于不同的范围大小。

我不知道如何在我的选择中选择最后一行下方的行并设置格式。

到目前为止我的代码是:

Selection.CurrentRegion.Select

Selection.Rows("1:1").Interior.Color = 12155648

With Selection.Rows("1:1").Font

    .ThemeColor = xlThemeColorDark1

    .Bold = True

End With



Selection.CurrentRegion.Select

Selection.Cells(Selection.Rows.Count, Selection.Columns.Count).Select

   

Selection.Interior.Color = 12632256

Selection.Font.Bold = True

Selection.Range("A1").Value = "Total"

我想要发生的事情:

Original

Desired Formatting

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    把它变成一个实际表格怎么样

    Sub Demo()
        With ActiveSheet.ListObjects.Add(xlSrcRange, ActiveCell.CurrentRegion, , xlYes)
            .Name = "MyTable" ' optional
            .ShowTotals = True
        End With
    End Sub
    

    之前

    之后

    【讨论】:

    • 我喜欢你的头在哪里,但是这样格式化表格的目的是为了匹配一份非常冗长的年度报告中的现有表格格式。并与往年这些表格的格式相匹配。
    【解决方案2】:

    不,这不是一个常见的问题,因为大多数程序员在第二天(即您的日程安排中的明天)学习不要“选择”任何东西,而是使用 Range 对象。然后你的代码看起来更像这样:-

    Private Sub Snippet()
    
        Dim Rng     As Range
    
        With Selection.CurrentRegion
            .Rows(1).Interior.Color = 12155648
            With .Rows(1).Font
                .ThemeColor = xlThemeColorDark1
                .Bold = True
            End With
            Set Rng = ActiveSheet.Cells(.Row + .Rows.Count, .Column).Resize(1, .Columns.Count)
        End With
        
        With Rng
            .Interior.Color = 12632256
            .Font.Bold = True
            .Cells(1).Value = "Total"
        End With
    End Sub
    

    【讨论】:

    • 这正是我想要的。谢谢先生。
    【解决方案3】:

    您可以使用以下方法,假设您的表格从B4开始:

    Sub ty()
    
    Dim lastrow As Long
    
    lastrow = Sheet1.Range("B4").End(xlDown).Row + 1
    
    With Sheet1.Range("B4").Resize(1, 5)
        .Interior.Color = 12155648
        .Font.ThemeColor = xlThemeColorDark1
        .Font.Bold = True
    End With
    
    Sheet1.Cells(lastrow, 2).Value = "Total"
    
    With Sheet1.Cells(lastrow, 2).Resize(1, 5)
        .Interior.Color = 12632256
        .Font.Bold = True
    End With
    
    
    End Sub
    

    【讨论】:

    • 或许更好:lastRow = Sheet1.Range("B" & Sheet1.Rows.Count).End(xlUp).Row + 1
    • 我试图制作宏,以便它可以在工作表中任何位置开始的任何表格上工作。
    • @BigBen,太棒了,反向操作。但是当前几行为空Sheet1.UsedRange.Rows(Sheet1.UsedRange.Rows.Count).Row 时,有更好的方法来找到最后一行,我很久以前在 Stackoverflow 问题之一上找到了这个但无法追溯它,这是我得到的另一个链接stackoverflow.com/questions/40650508/find-last-row-in-range
    • @998024562165,是的,您可以根据您的表格更改范围,请尝试一下
    • 不,UsedRange 不可靠,请参阅stackoverflow.com/questions/11169445/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    相关资源
    最近更新 更多