Excel / VBA查找字符串并复制偏移量单元格

时间:2018-08-30 13:12:54

标签: excel vba

我需要一小部分VBA来完成以下任务, 搜索特定的字符串,例如(“新应用程序”),然后复制偏移量为(0,2)和(0,5)的单元格。因此,如果在A34中找到“新应用程序”,那么我需要复制D34和J34…

任何帮助,不胜感激。

到目前为止,我所拥有的一切如下,但我确定如何复制offset(0,5)。.

Sub test()
Cells.Find(What:="NB ASDA Applications", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate
    ActiveCell.Offset(0, 2).Select
    Selection.Copy

其余的代码,重新粘贴等我已经有了,我只需要对上述内容进行一小部分修改即可。

非常感谢

1 个答案:

答案 0 :(得分:1)

在这种情况下,使用变量会很有帮助。

Sub test()
    'make a variable called foundrange that is of type "Range"
    Dim foundRange as Range

    'set this variable based on what is found: (note we remove the 'activate' here
    Set foundRange = Cells.Find(What:="NB ASDA Applications", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False)

    'You can copy now and do whatever you want. Say you want to copy these values to Sheet2!A1 and B1, respectively:
    Sheet2.Range("A1").Value = foundRange.OFfset(0,2).value
    Sheet2.Range("B1").Value = foundRange.Offset(0,5).value 

    'Or copy to the clipboard -- haven't tested this union, but I think it should work
    Union(foundRange.Offset(0,2), foundRange.Offset(0,5)).Copy  

    'Or copy just one and do something
    foundRange.Offset(0,2).Copy
    'do something

    'Copy the other one and do something
    foundRange.Offset(0,5).Copy
    'do something