【问题标题】:Having trouble with my For and If Statements我的 For 和 If 语句有问题
【发布时间】:2017-06-23 18:23:43
【问题描述】:

我正在尝试在单击搜索按钮的地方做一些事情,它会在包含 10,000 个项目的工作表中搜索单元格“A1”的值,然后用我的信息从该行信息中填充我想要的所有数据到工作表中搜索框。我遇到的问题是,当我搜索一个项目并填充它应该填充的行时,然后我去搜索另一个项目,它只会覆盖第一个项目。我想要它,所以它会向下移动一行,所以当我去搜索第 2、3 甚至第 4 项时,它们都在不同的行中。我将在此处包含我的代码,所以如果您能提供帮助,那就太好了。我尝试过使用 Offset,但仍然没有成功。

Sub SearchBox()

Dim erow As Long
Dim ws As Worksheet
Dim lastrow As Long
Dim count As Integer

lastrow = Sheets("Charlotte Gages").Cells(Rows.count, 1).End(xlUp).Row

For x = 2 To lastrow
i = 3
If Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1") Then
Sheets("Gages").Cells(i, 1) = Sheets("Charlotte Gages").Cells(x, 1)
Sheets("Gages").Cells(i, 2) = Sheets("Charlotte Gages").Cells(x, 2)
Sheets("Gages").Cells(i, 3) = Sheets("Charlotte Gages").Cells(x, 3)
Sheets("Gages").Cells(i, 4) = Sheets("Charlotte Gages").Cells(x, 4)
 Sheets("Gages").Cells(i, 5) = Sheets("Charlotte Gages").Cells(x, 5)
Sheets("Gages").Cells(i, 6) = Sheets("Charlotte Gages").Cells(x, 6)
count = count + 1
If Sheets("Charlotte Gages").Cells(x, 1) = "Found" Then
    i = 3 + 1

End If

 Next x


If count = 0 Then
MsgBox ("Cannot Find Gage, Please check Gage ID")

End If

End Sub

【问题讨论】:

    标签: excel vba for-loop if-statement


    【解决方案1】:

    你的增量是错误的:

    Sub SearchBox()
    Dim lastrow As Long
    dim i as long, x as long
    
    lastrow = Sheets("Charlotte Gages").Cells(Rows.count, 1).End(xlUp).Row
    i = 3
    For x = 2 To lastrow
    
        If Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1") Then
            Sheets("Gages").Cells(i, 1).Resize(,6).Value = Sheets("Charlotte Gages").Cells(x, 1).Resize(,6).Value            
            i = i + 1
        End If
    
     Next x
    
    
    If i = 3 Then
        MsgBox ("Cannot Find Gage, Please check Gage ID")    
    End If
    
    End Sub
    

    【讨论】:

    • @Jmaragno 如果可行,请单击答案旁边的复选标记,将其标记为正确。
    • 由于某种原因,当我在搜索中输入一个新条目时,它仍然只是覆盖了前一个条目
    • 然后您需要更改i = 3 以找到Gages 上的最后一行,就像使用Charlotte Gages 一样。 i = Sheets("Gages").Cells(Rows.count, 1).End(xlUp).Row + 1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 2017-02-11
    • 2014-01-23
    • 1970-01-01
    • 2020-03-24
    • 2017-07-19
    相关资源
    最近更新 更多