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

问题描述 投票:-1回答:1

我需要一小段VBA来执行以下操作,例如搜索特定字符串(“新应用程序”),然后复制单元格offset(0,2)和(0,5)。因此,如果在A34中找到“新应用程序”,那么我需要复制D34和J34 ......

任何帮助,非常感谢。

到目前为止我所有的一切如下,但我确定如何复制偏移量(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

其余的代码,重新粘贴等我已经拥有,我只需要将一小部分修改为上面的内容。

非常感谢

excel vba
1个回答
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 
© www.soinside.com 2019 - 2024. All rights reserved.