我的For和If语句出现问题

时间:2017-06-23 18:23:44

标签: excel vba for-loop if-statement

我正在尝试点击我的搜索按钮,然后在10,000个项目的工作表中搜索单元格“A1”的值,然后将我想要的所有数据从该行信息填充到工作表中搜索框。我遇到的问题是,当我搜索一个项目并填充它应该的行时,我会去搜索另一个项目,它只会覆盖第一个项目。我想要它所以它将向下移动一条线,所以当我去搜索第二,第三甚至第四项时,它们都在不同的行中。我会在这里包含我的代码,所以如果你能提供帮助,那就太好了。我尝试过使用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

1 个答案:

答案 0 :(得分:3)

你的增量是错误的:

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
相关问题