您好我在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
[编辑]:这是在尝试建议的解决方案后我的问题的屏幕截图:
Find
找到的单元格,而是将该单元格的行传递给名为myRow
的变量,并在另一个函数中使用此变量来定义所需的范围。myRange
之类的变量,并在其余代码中使用它而不是使用Selection
。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
中最后一个单元格的列与整个表格中的最后一列不相同(请参见屏幕截图),那么您有两个选择来定义您的lastCol
:
lastCol
定义为行myRow
的最后一列(屏幕截图1),在这种情况下,您可以将代码保持原样。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,如果最后一个单元格的列在所有行中都相同,则可以忽略最后一段。
关于如何避免选择/选择/激活/ 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