【问题标题】:Creating a dynamic loop for cells.find function为 cells.find 函数创建动态循环
【发布时间】:2013-07-30 14:17:14
【问题描述】:

创建一个宏,该宏将在工作表 A 中获取 cell.value(字符串),然后转到工作表 B,使用 cells.find 方法找到与字符串匹配的单元格。

例子

SheetA.activecell.value = "Harry Potter"
set myvar = SheetA.activecell.value
sheetB.select
Cells.Find(What:=myvar, After:=ActiveCell, LookIn:=xlValues, _ 
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
    MatchCase:=False).Select 

假设上述语法正确,工作表A中包含字符串“哈利波特”的单元格将被自动选中。

这就是我的问题所在。我想对整个列进行循环,为列中的每个单元格执行Cells.Find 函数。

例如,SheetA.cells(3 ,1) 包含“哈利波特”。在每次循环完成时使用偏移函数,包含要找到的值的单元格将偏移 1 行。

因此,在循环的下一次迭代中,SheetA 中的Cells(4, 1) 将包含要在cells.find 函数中使用的值。

比如说,那个值是字符串“Iphone Charger”。然后,cells.find(what:=myvar (Basically myvar = "Iphone Charger") 将在工作表 B 中执行。

在工作表 A 的列中以此类推。

其次,我想复制工作表 A 中的某些值。

场景:

If "Harry Potter" is found in sheetA then
     Do an `activecell.offset` function to copy some values in the same row as the cell in sheet A and 
     Copy those values to worksheet B using Copy destination
Else if "Harry Potter" can be found then 
     Jump to the next cell value.
End if 

Keep looping until worksheet B hits an empty cell, that is cells(X , 1).value = ""

Then the whole macro ends

一直在杀死我的脑细胞来解决这个问题,如果论坛中的任何人能帮助我,我将不胜感激。

【问题讨论】:

  • 看起来您确实拥有完成宏所需的大部分组件...?其他人提供的格式应该可以帮助您进一步构建它。您是否已创建初始宏?它会给您带来什么错误?
  • 你有任何示例代码可以分享吗? Excel vba 不会提示任何错误,但宏在到达此部分时会停止循环。 Columns("A:A").Select Cells.Find(What:=lookfor, After:=ActiveCell, LookIn:=xlValues, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False ).选择
  • Cells.Find 将在整个工作表中搜索lookfor第一个 实例。要在定义的范围内继续搜索,您需要使用 FindNext,您可以在 SF 上找到几个如何使用它的示例。如果您发布更多实际代码,那么我们也可以提供帮助
  • user2451335,您是否需要在 sheetB 中找到多个“哈利波特”实例,或者您只是想遍历 A 列的值,为每个值找到一个实例?您能否向我们展示您用于循环的实际代码?

标签: vba excel ms-office excel-2010


【解决方案1】:

我建议在单元格的主循环中使用 For Each 构造,其中包含要在工作表 A 中找到的值。在伪代码中:

For each cell in column A of sheet A
    With the sheet B range to look in
        If cell value is "" 
            Exit the sub
        Else
            result = .find the cell value
            If the find is successful ("Not result is nothing") 
                Copy sheetA.cells(cell.row, <column of interest>) to sheet B
                Copy ... (cell.row,<another column of interest>) ...
            End the If
         End the if
    End the with 
Next cell

请注意,这只会查找工作表 A 的 A 列中每个值的一个实例。

正如 Jaycal 所指出的,您需要使用 FindNext 在第一个实例之后查找其他实例。

基本思想是找到第一个实例并保存其地址,然后使用带有 FindNext 的 do 循环来查找更多实例。 do 循环一直执行,直到 FindNext 找到与您为找到的第一个实例保存的地址相同的单元格。

有关这方面的代码示例,请参阅 this explananationthis one,以及可以在网络上找到的许多其他代码。

【讨论】:

  • chuff:你能不能更含蓄地说一句:用工作表 B 范围来查看,似乎并没有得到它。
  • 实际上,我的意思是字面意思。假设工作表 B 中的值在 B 列中。您可以将 With 编码为 With Worksheets("B").Range("B:B")。然后使用 .Find(...) 会将搜索限制在工作表 B 的 B 列。
猜你喜欢
  • 2021-12-21
  • 1970-01-01
  • 2021-04-09
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多