使用Excel VBA搜索一个单元格中的一个值,并在同一行上搜索另一个单元格以获取另一个值

时间:2018-01-09 18:31:34

标签: excel-vba vba excel

我正在研究一个大型的VBA脚本,但是当我需要VBA脚本检查这个逻辑时,我遇到了问题:

If Cell AC2 = "PastDue" And Cell W2 <> "Risk Accepted" on Sheet1 Then Copy row to Sheet2.

这是我到目前为止的代码:

Sub PastDue()
Application.ScreenUpdating = False
Application.StatusBar = "Job Updating"

Dim lr As Long
Dim lr2 As Long
Dim r As long
Dim ws1 As Worksheet1
Dim ws2 As Worksheet2

Application.ScreenUpdating= False
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
N = 1
lr = ws1.Cells(Rows.Count, "AC").End(x1Up).Row 'Used to search column AC
lr = ws1.Cells(Rows.Count, "W").End(x1Up).Row 'This errors out when ran and was a line I added in to check the second column
lr2 = ws2.Cells(Rows.Count, "A").End.x1Up).Row

    For r = 2 To lr
        If ws1.Range("AC" & r).Value = "PastDue" Then
            If ws1.Range ("W" & r).Value <> "Risk Accepted" Then 'I added this to search for the second piece of the logic
                ws1.Rows(r).Copy Destination:=ws2.Range("A" & N + 1)
            N = ws2.Cells(Rows.Count, "A").End(xlUp).Row
            End If
        End If
   Next r
Sheets("Sheet2").Select
Application.StatusBar = False
Application.ScreenUpdating = True
End Sub

这是一个稍微修改过的代码,只在一列中查找单个值时才能正常工作

1 个答案:

答案 0 :(得分:1)

我在一些模拟数据上测试了你的代码,它似乎除了一些奇怪的错误之外。在将代码复制到StackOveflow时,或者如果它们确实存在于您的VBA中,我不确定这些错误是否是疏忽。如果这确实是你的代码,我不确定你的代码在搜索单个值时是如何工作的。

  1. Dim的工作表Worksheet1Worksheet2。这些不是类名。将行更改为:Dim ws1 as WorksheetDim ws2 as Worksheet
  2. 您传递给End函数的论点是x1up(请注意,您使用的是第一个而不是l字母。
  3. 当我更改这两项时,代码似乎有效。我强调“似乎”这个词,因为我不确定你的错误是什么。你需要解释。

    我最终使用的代码:

    Sub PastDue()
    Application.ScreenUpdating = False
    Application.StatusBar = "Job Updating"
    
    Dim lr As Long
    Dim lr2 As Long
    Dim r As Long
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    
    Application.ScreenUpdating = False
    Set ws1 = Sheets("Sheet1")
    Set ws2 = Sheets("Sheet2")
    N = 1
    lr = ws1.Cells(Rows.Count, "AC").End(xlUp).Row 'Used to search column AC
    lr = ws1.Cells(Rows.Count, "W").End(xlUp).Row 'This errors out when ran and was a line I added in to check the second column
    lr2 = ws2.Cells(Rows.Count, "A").End(xlUp).Row
    
        For r = 2 To lr
            If ws1.Range("AC" & r).Value = "PastDue" Then
                If ws1.Range("W" & r).Value <> "Risk Accepted" Then  'I added this to search for the second piece of the logic
                    ws1.Rows(r).Copy Destination:=ws2.Range("A" & N + 1)
                N = ws2.Cells(Rows.Count, "A").End(xlUp).Row
                End If
            End If
       Next r
    Sheets("Sheet2").Select
    Application.StatusBar = False
    Application.ScreenUpdating = True
    End Sub