查找并偏移以将值复制到第二个工作表的末尾

时间:2018-12-02 13:11:04

标签: excel vba

我有两个Excel文件。
我正在尝试执行以下操作:

  1. 在第一张中搜索值。
  2. 找到项目后,请使用offset来拾取相邻的值,即左侧4列(同一行)
  3. 将值(在第2步中)添加到D行结尾处的第二张纸上

努力进行第三步。
我找不到方法或数据成员。

Sub findOne()

Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = ThisWorkbook.Sheets("one") ' ref to sheet one
Set ws2 = ThisWorkbook.Sheets("two") ' ref to sheet two

Dim rng As Range

With ws1

    ' use find on range H
    Set rng = Range("H1:H200").Find(What:="busaoc", LookAt:=xlPart)

    '- doesn't like this   
    ws2.Range("D2").End(xlDown).Offset(1, 0) = ws1.rng(.Offset(0, -4))

End With

end Sub

1 个答案:

答案 0 :(得分:0)

您没有使用您的With块,但由于没有必要 if 这是您的完整代码,因此我在这里将其删除。还已对此进行了修改,以确保不会在实际上找不到您的值的情况下崩溃。

Sub findOne()

Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("one")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("two")
Dim rng As Range, LR As Long

Set rng = ws1.Range("H1:H200").Find(What:="busaoc", LookAt:=xlPart)

If rng Is Nothing Then
    MsgBox "Value not found"
Else
    LR = ws2.Range("D" & ws2.Rows.Count).End(xlUp).Offset(1).Row
    ws2.Range("D" & LR).Value = rng.Offset(0, -4).Value
End If

End Sub