VBA ActiveCell动态调整大小

问题描述 投票:1回答:2

您好我在excel电子表格中创建了以下代码来格式化Grand Total Row。我的问题是我想从Grand Total选择动态细胞,因为我没有总共15列。我尝试使用ActiveCell,但它没有用。任何人都可以帮我改变这段代码以满足我的需要吗?

Range("A1").Select
FindRow1 = Range("A:A").FIND(What:="Grand Total", LookIn:=xlValues, LookAt:=xlWhole).Activate
ActiveCell.Resize(, 15).Select

'Range(ActiveCell, Cells(, ActiveCell.End(xlToRight).Column)).Select

Selection.Font.Bold = True

With Selection.Interior
    .Pattern = xlSolid
     .PatternColorIndex = xlAutomatic
     .ThemeColor = xlThemeColorAccent6
     .TintAndShade = 0.399975585192419
    .PatternTintAndShade = 0

End With

Selection.Font.Size = 12

[编辑]:这是在尝试建议的解决方案后我的问题的屏幕截图:

enter image description here

excel vba
2个回答
2
投票
  1. 您不必选择范围。只要确定你正在使用的范围的地址,你就是好的。
  2. 如果你指定你正在使用的工作表会更好,所以如果工作簿中有多个工作表,你仍然可以使用正确的工作表。
  3. 不是激活使用Find找到的单元格,而是将该单元格的行传递给名为myRow的变量,并在另一个函数中使用此变量来定义所需的范围。
  4. 一旦定义了所需的范围,将其传递给myRange之类的变量,并在其余代码中使用它而不是使用Selection
  5. 要使您的范围动态更改其大小(假设您希望您的范围有一行和该行的所有已填充单元格),那么您需要找到表格中最后一个填充单元格的列,将其传递给变量lastCol并用它来定义你的范围。
Sub formatRange()

    Dim ws As Worksheet
    Dim myRow As Long, lastCol As Integer, myRange As Range

    Set ws = ThisWorkbook.ActiveSheet  'Change this to the name of the sheet you're working with

    myRow = ws.Range("A:A").Find(What:="Grand Total", LookIn:=xlValues, LookAt:=xlWhole).Row 'The row that has "Grand Total"
    lastCol = ws.Cells(myRow, Columns.Count).End(xlToLeft).Column 'The column of the last filled cell in `myRow`

    Set myRange = ws.Range("A" & myRow).Resize(1, lastCol) 'The desired range has 1 row and (lastCol) columns

    myRange.Font.Bold = True

    With myRange.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = 0.399975585192419
        .PatternTintAndShade = 0
    End With

    myRange.Font.Size = 12

End Sub
  • 考虑这种情况:

如果行myRow中最后一个单元格的列与整个表格中的最后一列不相同(请参见屏幕截图),那么您有两个选择来定义您的lastColTable Screenshot 1&2

  1. 您可以将lastCol定义为行myRow的最后一列(屏幕截图1),在这种情况下,您可以将代码保持原样。
  2. 您可以将其定义为整个表的最后一列(屏幕截图2),在这种情况下,您必须使用以下内容替换上面的lastCol行: 'The column of the last filled cell in the whole table lastCol = ws.Cells.Find(What:="*", _ After:=Range("A1"), _ LookAt:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious).Column

P.S,如果最后一个单元格的列在所有行中都相同,则可以忽略最后一段。


1
投票

关于如何避免选择/选择/激活/ ActiveXXX模式以及如何使用嵌套的另一个示例...结束:

With Range("A1", Range("A:A").Find(What:="Grand Total", LookIn:=xlValues, LookAt:=xlWhole).End(xlToRight))

    With .Font
        .Bold = True
        .Size = 12
    End With 

    With .Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = 0.399975585192419
        .PatternTintAndShade = 0
    End With

End With 
© www.soinside.com 2019 - 2024. All rights reserved.