(VBA)适用于所有人,除了一个特定的

时间:2017-04-26 10:06:57

标签: excel excel-vba excel-formula vba

大家好我在excel上使用VBA模块制作了一个按钮,该代码适用于活动工作表,但我想要的是应用于更多工作表,而不仅仅是放置按钮的活动工作表。

Sub Botón1_Haga_clic_en()
    Call Worksheet_Calculate
End Sub


'apply cells colors from single-cell formula dependencies/links
Private Sub Worksheet_Calculate()
    Dim Cel       As Range
    Dim RefCel  As Range

    On Error Resume Next

    For Each Cel In ActiveSheet.UsedRange
        If Cel.HasFormula Then
            Set RefCel = Evaluate(Mid(Cel.Formula, 2))
            Cel.Interior.Color = RefCel.Interior.Color
        End If
    Next Cel

End Sub

2 个答案:

答案 0 :(得分:0)

您的问题可以转换为如何循环覆盖所有工作表并忽略其中一个?

这是一个很好的方法:

Option Explicit
Option Private Module

Public Sub TestMe()

    Dim wks As Worksheet

    For Each wks In ThisWorkbook.Worksheets
        If wks.name = "main" Then
            Debug.Print "Do nothing here, this is the active sheet's name"
        Else
            Debug.Print wks.name
        End If

    Next wks

End Sub

非常确定,您应该能够在代码中使用它。

答案 1 :(得分:0)

尝试以下代码:

Option Explicit

Sub Botón1_Haga_clic_en()

Dim wsName As String
Dim ws As Worksheet

wsName = ActiveSheet.Name

For Each ws In ThisWorkbook.Worksheets
    If Not ws.Name Like wsName Then '<-- is worksheet's name doesn't equal the ActiveSheet's
        ApplyCellColors ws ' <-- call you Sub, with the worksheet object
    End If
Next ws

End Sub

'=======================================================================    
'apply cells colors from single-cell formula dependencies/links

Private Sub ApplyCellColors(ws As Worksheet)

    Dim Cel       As Range
    Dim RefCel  As Range

    On Error Resume Next

    For Each Cel In ws.UsedRange
        If Cel.HasFormula Then
            Set RefCel = Evaluate(Mid(Cel.Formula, 2))
            Cel.Interior.Color = RefCel.Interior.Color
        End If
    Next Cel

End Sub