Excel VBA在一行中两列中查找数据

时间:2018-09-03 22:27:19

标签: excel vba excel-vba

我正在尝试使此代码查找其中列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

结束子

谢谢

1 个答案:

答案 0 :(得分:1)

你很近。我将currentrow更改为i,因为它易于使用。您还应该使表格合格。每当您引用目标表上的对象时,请使用ws

区分大小写也毫无意义。即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

您也可以像这样将所有三个条件合并为一行

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