【问题标题】:VBA code to copy value next to searched value将值复制到搜索值旁边的 VBA 代码
【发布时间】:2014-12-21 13:49:16
【问题描述】:

我是 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 中找到值..

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    考虑:

    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
    

    【讨论】:

      【解决方案2】:

      首先,您应该始终使用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 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-03
        • 2019-11-27
        • 1970-01-01
        • 2016-04-20
        • 1970-01-01
        • 2019-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多