我正在尝试浏览excel电子表格中的一列空单元格,以便找到找到“是”字样的行。然后,在特定行中找到该单词时,例如在单元格D23中,我希望它通过一列到单元格E23并将该单元格中的值粘贴到单元格B100中。这是我到目前为止所做的,但它似乎没有正常运作:
Sub Test3()
Dim x As String
x = "Yes"
' Dim found As Boolean
' Select first line of data.
Range("D4").Select
' Set search variable value.
' Set Boolean variable "found" to false.
found = False
' Set Do loop to stop at empty cell.
Do Until ActiveCell.Value = x
' Check active cell for search value.
If ActiveCell.Value = x Then
Range("B100").Value = ActiveCell.Offset(0, 1).Value
found = True
Exit Do
End If
' Step down 1 row from present location.
ActiveCell.Offset(1, 0).Select
Loop
' Check for found.
If found = True Then
MsgBox "Value found in cell " & ActiveCell.Address
Else
MsgBox "Value not found"
End If
End Sub
谢谢!
答案 0 :(得分:2)
正如@tigeravatar在他的评论中提到的,你可能最好使用Excel的本机功能,但是,如果你想通过VBA这样做,你可以使用Find更轻松有效地完成这项工作。如果找到则返回范围的函数,否则返回“Nothing”。
使用它,你可以测试看你得到了什么。试试这个:
Sub Test3()
Dim x As String
Dim rng As Range
x = "Yes"
Set rng = Range("D4:D10000").Find(x)
If Not rng Is Nothing Then
Range("B100").Value = rng.Offset(0, 1).Value
MsgBox "Value found in cell " & rng.Address
Else
MsgBox "Value not found"
End If
End Sub
希望它成功。