将范围复制到变量,然后偏移该范围变量并将值保存到另一个变量

Copy a range to a variable, then offset that range variable and save the value to another variable

因此,我尝试搜索具有特定字符串的单元格范围,然后将单元格的内容复制到其下方的 3 个空格以保存到另一个电子表格。

到目前为止我的代码是这样做的,但是需要 select 单元格然后用 variableName.Select 偏移它然后 ActiveCell.Offset(blahblah).[=11 似乎很笨拙=]

是否可以通过调用 variableName.Offset(3,0).Value 或类似性质的东西来清理代码来偏移(并从中提取值)所需的单元格?

这是我目前的代码,在此先感谢您的帮助!

    Dim ra As Range

Sheets("starting").Activate
    
Set ra = Cells.Find(What:="Product Name", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True)
'finds correct cell
  
  If ra Is Nothing Then
        MsgBox ("Search Error: Not found")
        Else
        MsgBox (ra.Address) ' to test
    End If

Dim foundCell

ra.Select

ActiveCell.Offset(3, 0).Select

'foundCell = Cells(ra).Offset(0, 3) '.Address '.value        '   <<< not grabbing the data

foundCell = ActiveCell.Value


MsgBox foundCell   'shows the value of the desired cell now! (to test)

Sheets("testing").Activate

Sheets("testing").Cells(2, "F").Value = foundCell      '2,"F" will be replaced by a range stored in a variable

这将做同样的事情:

Sub Test()

    Dim ra As Range
    Set ra = Sheets("starting").Cells.Find(What:="Product Name", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True)
    If ra Is Nothing Then
        MsgBox ("Search Error: Not found")
    Else
        MsgBox (ra.Address) ' to test
        Sheets("testing").Cells(2, 6) = ra.Offset(3, 0)
    End If

End Sub  

我已将其复制到 If ra Is Nothing 测试中的 testing sheet。

按照您的代码,它会显示消息 “搜索错误:未找到”,然后尝试从未找到的值偏移三行,给出 Object variable or With block variable not set错误。