我是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中找到值。
答案 0 :(得分:0)
考虑:
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
答案 1 :(得分:0)
首先,您应始终使用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