【问题标题】:How to find and apply format in multiple sheets in excel?如何在excel中的多个工作表中查找和应用格式?
【发布时间】:2022-11-14 19:26:49
【问题描述】:

我想找到周数并将格式应用于该单元格。周数是使用 Sheets("Program").Range("N3") 中的 weeknum 公式自动生成的。

我有5张。在第一张表Overview 中,数据位于第 8 行并且格式有效。在表 2 到 5 中,数据位于第 4 行。因此,我选择了所有 4 张表并使用相同的逻辑。但格式不适用于工作表BBBCCCDDD

我的程序没有显示任何错误并且无法正常工作。谁能帮我?

Sub FindandFormat()  
    Dim ws1, ws2, ws3 As Worksheet
    Dim CW As String
    Dim rng2, rng1 As Range
    
    Set ws1 = ThisWorkbook.Worksheets("Overview")
    Set ws2 = ThisWorkbook.Worksheets("AAA")
    
    ' "Format to show the actual week in every sheet"
    CW = "W" & ThisWorkbook.Worksheets("Program").Range("N3").Value - 1
    
    With ws1
        Set rng1 = .Rows("8:8").Find(What:=CW, LookIn:=xlValues)
        With rng1.Interior
            .ThemeColor = xlThemeColorAccent6
            .TintAndShade = 0.599993896298105
        End With
    End With
    
    With ws2
        Set rng2 = .Rows("4:4").Find(What:=CW, LookIn:=xlValues)
    
        ThisWorkbook.Sheets(Array("AAA", "BBB", "CCC", "DDD")).Select
    
        With rng2.Interior
            .ThemeColor = xlThemeColorAccent6
            .TintAndShade = 0.599993896298105
        End With
    End With
End Sub

【问题讨论】:

  • 只在床单上循环可能更简单?

标签: excel vba excel-2016


【解决方案1】:

请注意,如果您声明Dim ws1, ws2, ws3 As Worksheet,则只有ws3Worksheet 类型,而其他的都是Variant 类型。在 VBA 中你需要指定一个类型每一个变量或默认为VariantDim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet。您的Range 也是如此。

此代码中的问题是选择这些工作表只会选择它们。

With ws2
    Set rng2 = .Rows("4:4").Find(What:=CW, LookIn:=xlValues)

    ThisWorkbook.Sheets(Array("AAA", "BBB", "CCC", "DDD")).Select

    With rng2.Interior
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = 0.599993896298105
    End With
End With

您将格式应用于With rng2.Interiorrng2 对使用.Rows("4:4")…With ws2 的引用,因此显然仅适用于ws2!无论选择哪个工作表,它都会将其应用于ws2

相反,您需要遍历工作表并将格式应用于每个工作表:

Dim WorksheetNames As Variant  ' define the worksheet names you want the format to apply to
WorksheetNames = Array("AAA", "BBB", "CCC", "DDD")

Dim WorksheetName As Variant
For Each WorksheetName In WorksheetNames  ' loop through all worksheet names in the array
    Dim FoundAt As Range  ' try to find CW in each worksheet
    Set FoundAt = ThisWorkbook.Worksheets(WorksheetName).Rows("4:4").Find(What:=CW, LookIn:=xlValues)
    
    ' check if CW was found otherwise show error message
    If Not FoundAt Is Nothing Then
        With FoundAt.Interior  ' perform format change
            .ThemeColor = xlThemeColorAccent6
            .TintAndShade = 0.599993896298105
        End With
    Else
        MsgBox """" & CW & """ was not found.", vbOKonly
    End If
Next WorksheetName

【讨论】:

    猜你喜欢
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    相关资源
    最近更新 更多