使用For循环冷凝代码?

时间:2017-09-29 11:43:58

标签: vba excel-vba excel

所以我创建了一个模块来查找工作表中的文本字符串以打印到另一个工作表中,代码工作但是感觉很麻烦,我必须多次运行代码才能得到我想要的结果,我知道一个For陈述是我应该怎么做但我只是想检查。这是当前的代码

Sub FindRANumbers()
Dim RA1Range As Range
emptyRow = WorksheetFunction.CountA(Sheet3.Range("A:A")) + 1
Sheet2emptyRow = WorksheetFunction.CountA(Sheet2.Range("H:H"))

'Find Checkbox values and paste them into Sheet 3
Set RA1Range = Sheet2.Cells.Find("RA0001")
Set RA1Check = Sheet3.Cells.Find("RA0001")
If Not RA1Check Is Nothing Then

ElseIf Not RA1Range Is Nothing Then
    Sheet3.Cells(emptyRow, 1).MergeArea.Value = "RA0001"
End If

End Sub

它需要遍历Sheet2 H:H中的行数。

我不太熟悉For循环,但是当我这样做时,我仍然需要多次运行代码

For i = 1 To Sheet2emptyrow
'Above code here'
Next i

我觉得我错过了一些非常简单的事情

提前感谢您的帮助。

编辑:

我认为我对这个问题的描述有点差,所以我附上了一张图片来展示我想要做的事情Screenshot of sheet 2 所以我想循环遍历Sheet 2中填充的多个单元格并为每个循环运行我的代码

我希望更有意义吗?对此抱歉,但感谢您的帮助

1 个答案:

答案 0 :(得分:2)

使用Range.Find Method (Excel)的示例,此代码找到For循环。

  

但是,请记住,如果您使用的是大型工作簿,则不是最快的搜索方式。这是performance test

你真的必须搜索整个Sheet3吗?因为它使它真的很懒。假设Sheet2列H是参考值,因此您在整个Sheet3上搜索它。

lastrow = Sheet2.Cells(Sheet2.Rows.Count, "H").End(xlUp).Row
For I = 8 To lastrow
   Set c = Sheet2.Cells(I, 8)
   With Sheet3
       Set cellFound = .Find(what:=c, LookIn:=xlValues, MatchCase:=False)
           If Not cellFound Is Nothing Then
               FirstAddress = cellFound.Address
               Do
                   'When value is found do something here
                   Debug.Print cellFound.Address 'To print the addresses of cells found
                   Set cellFound = .FindNext(cellFound)
               Loop While Not cellFound Is Nothing And cellFound.Address <> FirstAddress
            End If
   End With
 Next I

提取代码

H列的LastRow

lastrow = Sheet2.Cells(Sheet2.Rows.Count, "H").End(xlUp).Row

用于从第2行到第2列的H列的lastrow的循环

For I = 8 To lastrow
Next I

要搜索的值,因此使用变量I循环遍历所有行

Set c = Sheet2.Cells(I, 8)

搜索范围

With Sheet3
End With

使用.Find Method

的示例查找
           Set cellFound = .Find(what:=c, LookIn:=xlValues, MatchCase:=False)
           If Not cellFound Is Nothing Then
               FirstAddress = cellFound.Address
               Do
                   'When value is found do something here
                   Debug.Print cellFound.Address 'To print the addresses of cells found
                   Set cellFound = .FindNext(cellFound)
               Loop While Not cellFound Is Nothing And cellFound.Address <> FirstAddress
            End If
相关问题