您好,我创建了以下代码来格式化excel电子表格中的总计行。我的问题是我想从总计中选择动态单元格,因为我并不总是有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
[编辑]::这是尝试建议的解决方案后我的问题的屏幕截图:
答案 0 :(得分:1)
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
行中最后一个单元格的列与整个表格中的最后一列 NOT (参见截图)相同,则您有2种选择来定义{ {1}}:
lastCol
定义为lastCol
行的最后一列(屏幕截图1),在这种情况下,请按原样保留上面的代码。myRow
行:
lastCol
PS, 。如果最后一行单元格的列在所有行中都相同,则可以忽略此最后一段。
答案 1 :(得分:1)
关于如何避免“选择/选择/激活/ ActiveXXX”模式以及如何使用嵌套With ... End With结构的另一个示例:
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