【问题标题】:Trying to run 2 macros if cell has value如果单元格具有值,则尝试运行 2 个宏
【发布时间】:2022-01-23 01:25:25
【问题描述】:

我正在尝试添加到我现有的工作宏中。这个宏的上半部分只是把一些单元格变成大写。最后一行用于动态排序。现在我想添加功能,仅在更改单元格的 Q 列有值时才进行排序。

在我看来,添加类似于 If $Q "" 那么,然后是排序

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range
    If Not Intersect(Range("i2:n1000,r2:aa1000"), Target) Is Nothing Then
        Application.ScreenUpdating = False
        Application.EnableEvents = False
        For Each rng In Intersect(Range("j2:o1000,r2:aa1000"), Target)
            rng.Value = UCase(rng.Value)
        Next rng
        Application.EnableEvents = True
        Application.ScreenUpdating = True
    End If
   Range("g1").Sort Key1:=Range("g2"), Order1:=xlAscending, Header:=xlYes, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    一个可能的解决方案。我假设您要检查所选单元格 (TARGET) 行中 Q 列中的值。

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim rng As Range
        Dim Q_Cell as Range
    
    'Set the cell in the column "Q"
    
        Set Q_Cell = Range("Q" & Target.Row)
    
        If Not Intersect(Range("i2:n1000,r2:aa1000"), Target) Is Nothing Then
            Application.ScreenUpdating = False
            Application.EnableEvents = False
            For Each rng In Intersect(Range("j2:o1000,r2:aa1000"), Target)
                rng.Value = UCase(rng.Value)
            Next rng
            Application.EnableEvents = True
            Application.ScreenUpdating = True
        End If
    
    'Check whether there is something in the cell or not. Using VBA.Len is quicker then testing against an empty string (e.g. Q_Cell <> "").
    
        If VBA.Len(Q_Cell.Value) <> 0 then
    
    'If there is something in Q_Cell then sort the given range
    
            Range("g1").Sort Key1:=Range("g2"), Order1:=xlAscending, Header:=xlYes, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
        End If
    End Sub
    
    

    【讨论】:

    • 谢谢,这似乎可行。
    • @ham fam 感谢您的反馈。请将我的回答标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多