我对此很陌生,我正在制作条件格式来突出显示一行中所有值平均值以上的数字。
我需要将此格式应用于工作簿中所有工作表的所有行。
根据我收集的信息,我得到以下信息:
Sub AllSheets()
Dim ws As Worksheet
For Each ws In Worksheets
Range("A1:S1").Copy
For Each r In Selection.Rows
r.PasteSpecial (xlPasteFormats)
Next r
Application.CutCopyMode = False
Next ws
End Sub
但当我运行它时,它只应用于活动的选定单元格。我该如何解决这个问题?
答案1
您需要确保Range()
正在使用的实际上是中的范围ws
。否则,它只会在 Activesheet 上运行。
Dim ws As Worksheet
For Each ws In Worksheets
ws.Range("A1:S1").Copy
For Each r In Selection.Rows
r.PasteSpecial (xlPasteFormats)
Next r
Application.CutCopyMode = False
Next ws
End Sub
但是,这有效吗?它有点“紧”,主要是我想避免使用.Selection
Dim ws As Worksheet
For Each ws In Worksheets
ws.Range("A1:S1").Copy ' Or replace this with actual range, not just `Selection`
For Each r In ws.Range("A1:S1").Rows
r.PasteSpecial (xlPasteFormats)
Next r
Next ws
End Sub
编辑:刚刚意识到......为什么还要使用循环For each r
,因为无论如何你只使用一行?
答案2
我需要将此格式应用于工作簿中所有工作表的所有行。
确实,“知道如何提出正确的问题”需要练习。一旦您能做到这一点,就可以快速搜索:
循环浏览工作表 vba
Sub WorksheetLoop()
Dim WS_Count As Integer
Dim I As Integer
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
For I = 1 To WS_Count
' Insert your code here.
' The following line shows how to reference a sheet within
' the loop by displaying the worksheet name in a dialog box.
MsgBox ActiveWorkbook.Worksheets(I).Name
Next I
End Sub
参考:https://support.microsoft.com/en-us/help/142126/macro-to-loop-through-all-worksheets-in-a-workbook