首页 > 解决方案 > 具有两个条件的 Instr 函数

问题描述

我在 Sheet2 的单元格“A1”中有一个字符串,在 Sheet2 的单元格“A2”中有另一个字符串,我使用 LEFT 函数获取它们。这些在每次进口时都会发生变化。我试图在 Sheet1 的“AP”列中找到第一个字符串,在“AA”列中找到第二个字符串,并按这些值对工作表进行排序。然后我想复制整个 Sheet1 并将其粘贴到 Sheet2 中。我的代码什么也没给我。为什么错了?

Sub rc1()
    Dim lastrow As Long
    Dim i As Integer, icount As Integer
    Dim j As Integer, jcount As Integer
    Dim LResult As String

    LResult = Sheets("Sheet2").Range("A1")
    LResult = Left(LResult, 4)
    JResult = Sheets("Sheet2").Range("A2")
    JResult = Left(JResult, 2)

    lastrow = Sheets("Sheet1").Range("A30000").End(xlUp).Row

    Sheets("Sheet2").Activate
    Sheets("Sheet2").Range("B2:AQ" & lastrow).Select
    Selection.ClearContents

    icount = 1
    For i = 2 To lastrow
        For j = 2 To lastrow
            If InStr(1, LCase(Sheets("Sheet1").Range("AP" & i)), LCase(LResult)) <> 0 And InStr(1, LCase(Sheets("Sheet1").Range("AA" & j)), LCase(JResult)) <> 0 Then
                icount = icount + 1
                Sheets("Sheet2").Range("B" & icount & ":AQ" & icount) = Sheets("Sheet1").Range("A" & i & ":AP" & i).Value
            End If
        Next j
    Next i
End Sub

标签: excelvba

解决方案


我认为你的问题在这里:

LResult = Sheets("Sheet2").Range("A1")
LResult = Left(LResult, 4)
JResult = Sheets("Sheet2").Range("A2")
JResult = Left(LResult, 2)

最后一行不应该是JResult = Left(JResult, 2)吗?

目前它的工作方式,它将覆盖您从 sheet2 单元格 A2 分配的值,并在 sheet2 单元格 A1 中使用最左边的 2 个字符。如果该值没有出现在 AA 列中,那么您的 if 语句中的条件将永远不会评估为真。


推荐阅读