【问题标题】:Excel VBA Find data in two columns on a single rowExcel VBA 在单行的两列中查找数据
【发布时间】:2019-02-08 22:10:38
【问题描述】:

我试图让这段代码找到 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

结束子

谢谢

【问题讨论】:

  • 找到数据后,您想对它做什么?即,数一下?总结一下?返回一个值?
  • 我需要选择A列中的单元格然后调用一个子。
  • @Bofett 也许您应该更多地解释一下您的代码的用途(可能还有其他子代码)。您不需要Select 我评论中所述的任何内容。很有可能,您只是使用 Select 作为中间运算符。你已经在这里找到了你的问题的答案,所以你的下一个问题应该得到一个新的问题。
  • @urdearboy,你是对的。感谢您的帮助,这很完美。如果需要,我将处理该部分并开始一个新问题。

标签: vba excel


【解决方案1】:

你很亲密。我将currentrow 更改为i,因为它更容易多次使用。您还应该限定您的工作表。每当您引用目标工作表上的对象时,请使用 ws 对其进行限定

这也是区分大小写的。 IE。 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

【讨论】:

  • 好多了,谢谢!你能帮我忽略大小写吗?我希望它寻找大写和小写。此外,是否有一种简单的方法可以开始查看第 11 行而不是开始?再次感谢!
  • 您能详细说明一下吗?您想知道它是 Y、y、L 还是 l?如果是这样,我在解决方案中解决了这个问题。在顶部添加Option Compare Text,它将平等对待大写和小写
  • 更新为从第 11 行开始。只需将 For i = 1 to 更改为 For i = 11 to 。同样,icurrentrow 是相同的。每次看到i,想想行号
  • 再次感谢,我需要选择 A 列中的单元格,然后调用一个子。
  • 你不需要Select!你真正需要做什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多