复制搜索值旁边的值的VBA代码

复制搜索值旁边的值的VBA代码,vba,excel,Vba,Excel,我是VBA编码新手,我想为搜索的值复制同一行中的单元格 当我尝试访问时,我遇到了一个错误。例如,我想在我的xl表中找到abcd。 假设在单元格c12中找到abcd,我想复制单元格E12、F12中的值 我尝试使用偏移属性时出错 Private Sub FindingValues() Dim val As Variant val = InputBox(" Please Enter the value you want to search for") Set c = Cells

我是VBA编码新手,我想为搜索的值复制同一行中的单元格

当我尝试访问时,我遇到了一个错误。例如,我想在我的xl表中找到abcd。 假设在单元格c12中找到abcd,我想复制单元格E12、F12中的值

我尝试使用偏移属性时出错

Private Sub FindingValues()
    Dim val As Variant
    val = InputBox(" Please Enter the value you want to search for")
    Set c = Cells.Find(val, LookIn:=xlValues, MatchCase:=False)
    If Not c Is Nothing Then
    firstaddress = c.Address
    Do
    MsgBox "Value of val is found at " & c.Address
    Set c = Cells.FindNext(c)
    Loop While Not c Is Nothing And c.Address <> firstaddress
    End If

End Sub
在上面的代码中,我能够得到我搜索过的单元格的地址。我想找到行单元格值旁边的值。 就像我们假设在单元格c12中找到abcd一样,我想考虑d12、e12中的值。

考虑:

Public Sub FindingValues()
    Dim val As Variant
    val = InputBox(" Please Enter the value you want to search for")
    Set c = Cells.Find(val, LookIn:=xlValues, MatchCase:=False)
    If Not c Is Nothing Then
        firstaddress = c.Address
        Do
            MsgBox "Value of val is found at " & c.Address & vbCrLf & c.Offset(0, 1).Value & vbCrLf & c.Offset(0, 2).Value
            Set c = Cells.FindNext(c)
        Loop While Not c Is Nothing And c.Address <> firstaddress
    End If
End Sub

首先,您应该始终使用option explicit,因为这会产生有用的错误信息

其次,如果您知道类型,您应该尽量避免使用Variant。然而,这条规则也有例外。但是对于简单的程序来说,这是一个很好的规则

在您的代码上-您可以使用offset函数。第一个参数偏移行,第二个参数偏移列

试试这个

Option Explicit

Private Sub FindingValues()
    Dim val As Variant
    Dim c As Range
    Dim firstaddress As String

    val = InputBox(" Please Enter the value you want to search for")
    Set c = Cells.Find(val, LookIn:=xlValues, MatchCase:=False)
    If Not c Is Nothing Then
    firstaddress = c.Address
    Do
    MsgBox "Value of val is found at " & c.Address
    MsgBox "Value found at +1 column offset is " & c.Offset(0, 1).Value
    Set c = Cells.FindNext(c)
    Loop While Not c Is Nothing And c.Address <> firstaddress
    End If

End