【问题标题】:Insert Row when 2 conditions are met满足 2 个条件时插入行
【发布时间】:2021-06-27 10:11:11
【问题描述】:

我创建了下面的代码,其工作方式类似于 IF Col"B" 任何单元格 <> ""Col"L" 任何单元格 = "Leop" 然后将下面的行添加到活动单元格。

我的意思是我想要实现的是在 B 列中包含任何值的特定行之后插入单行,并且如果同一行中的 L 列包含 value =“Leop”。然后在该行之后添加行。

但出现错误。 Compile Error: Invalid use of property xlDown

您的帮助将不胜感激。

从这里:

到这里:

Sub firstcondition()

    Dim ws As Worksheet
    Dim LRow As Long
    Dim rng As Range
    Dim rng2 As Range
    Dim i As Long
    Dim p As Long
    Dim dat As Variant
    Dim datt As Variant
    Dim IRow As Long
    
    Set ws = Thisworkbooks.Sheets("Sheet2")
    
    With ws
    LRow = .Range("A" & .Rows.Count).End(xlUp).Row
    Set rng = .Range("B2:B" & LRow)
    Set rng2 = .Range("L2:L" & LRow)
    
    dat = rng
    datt = rng2
    IRow = Selection.Row
    
    For i = LBound(dat, 1) To UBound(dat, 1)
    For p = LBound(datt, 1) To UBound(datt, 1)
    
        If dat(i, 1) <> "" And datt(p, 1) = "Leop" Then
        Rows(IRow + 1).Select
        Selection.Insert Shift: xlDown
        End If
    
End Sub

它会像公式:

IF(AND(B2<>"",L2="Leop"),"InsertRowBelow to Row 2 If condition is met","")

并将其拖到最后一行。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    Thisworkbooks.Sheets("Sheet2") 应该是 Thisworkbook.Sheets("Sheet2") 并且在 Selection.Insert Shift:= xlDown 中缺少 =

    插入或删除行会改变最后一行的编号,所以从底部开始向上工作。

    Option Explicit
    Sub firstcondition()
    
        Dim ws As Worksheet, LRow As Long, r As Long
        Dim n As Long
        
        Set ws = ThisWorkbook.Sheets("Sheet2")
        With ws
            LRow = .Range("B" & .Rows.Count).End(xlUp).Row
            For r = LRow To 2 Step -1
                If .Cells(r, "B") <> "" And .Cells(r, "L") = "Leop" Then
                    .Rows(r + 1).Insert shift:=xlDown
                    n = n + 1
                End If
            Next
        End With
        MsgBox n & " rows inserted", vbInformation
    
    End Sub
    

    【讨论】:

    • 这很好用。谢谢@CDP1802 是的,我也看到了我的错误。感谢您强调。
    【解决方案2】:

    用自动过滤器试试这个,你不必遍历每一行。所以它会更快地处理更大的数据。

    Option Explicit
    Sub firstcondition()
    Dim ws As Worksheet
        Dim LRow As Long, cl As Range
        Set ws = ThisWorkbook.Sheets("Sheet2")
        LRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
        ws.Range("L1:L" & LRow).AutoFilter 1, "Leop"
        
        For Each cl In ws.Range("_FilterDatabase").SpecialCells(12).Cells
            If ws.Range("B" & cl.Row) <> "" Then
                cl.Offset(1).EntireRow.Insert Shift:=xlDown
            End If
        Next
        ws.AutoFilterMode = False
    End Sub
    

    【讨论】:

    • 仅当您尚未在同一张工作表的其他地方使用自动过滤器时才使用此选项。
    • 是的,这种方法很好。但是已经在使用过滤器。谢谢
    猜你喜欢
    • 2017-03-24
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2021-10-02
    • 2014-01-21
    相关资源
    最近更新 更多