Excel VBA在单行中的两列中查找数据

问题描述 投票:0回答:1

我试图使这段代码找到一列,其中列V不等于“Y”或“L”并且列A不是空白。我想我有点过分了,我确信有更简单的方法来检查行上的两个单元格。

Sub EndMove()
Dim Col1 As Integer, Col2 As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String, currentRowValue2 As String

Col1 = 22
Col2 = 1
rowCount = Cells(Rows.Count, Col1).End(xlUp).row

For currentRow = 1 To rowCount
    currentRowValue = Cells(currentRow, Col1).Value
    If currentRowValue <> "y" Or currentRowValue <> "l" Then
    currentRowValue2 = Cells(currentRow, Col2).Value
    If Not IsEmpty(currentRowValue2) Then
    Cells(currentRow, Col1).Select
    MsgBox "Move this?"
End If
End If
Next

结束子

谢谢

excel vba excel-vba
1个回答
1
投票

你很亲密我将currentrow更改为i,因为它更容易使用多次。您还应该对您的表格进行限定。无论何时您指的是目标表上的对象,都要使用ws进行限定

这也是值得一提的,这是区分大小写的。 I.E. Y <> y。如果你想忽略这种情况你可以将Option Compare Text放在Sub EndMove之上


Option Explicit

Sub EndMove()
Dim rowCount As Long, i As Long

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")

rowCount = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

'i refers to row number
For i = 11 To rowCount
    If ws.Range("V" & i) <> "Y" And ws.Range("V" & i) <> "L" Then
        If ws.Range("A" & i) <> "" Then
            'Do what with row i?
        End If
    End If
Next i

End Sub

您也可以将所有3个标准合并为一行,如此

For i = 11 To rowCount
    If ws.Range("V" & i) <> "Y" And ws.Range("V" & i) <> "L" And ws.Range("A" & i) <> "" Then
        'Do what with row i?
    End If
Next i
© www.soinside.com 2019 - 2024. All rights reserved.