我想搜索一个数据目录(包含在“目录”中,如果该数据与单元格“D3”中的项目匹配,我想将值“Mobile Phone”输出到“Sheet1”中的单元格“H3”。
这是我正在使用的:
Sub VBAScanner()
Dim productname As String
Dim finalrow As Integer
Dim i As Integer
finalrow = Sheets("Catalogue").Range("J3000").End(x1UP).Row
productname = Sheets("Sheet1").Range("D3").Value
For i = 5 To finalrow
If Sheets("Catalogue").Cells(i, 5) = productname Then
Sheets("Sheet1").Cell("H3").Value = "Mobile Phone"
End If
Next i
End Sub
谢谢
您可以使用“查找”以及更正xlUp
。另外,添加一些未找到的基本测试,最后一行小于5,或productname
为空。
Option Explicit
Public Sub VBAScanner()
Dim productname As String, finalRow As Long, found As Range, i As Long
productname = ThisWorkbook.Worksheets("Sheet1").Range("D3").Value
If productname = vbNullString Then Exit Sub
With ThisWorkbook.Worksheets("Catalogue")
finalRow = .Range("J3000").End(xlUp).Row
If finalRow < 5 Then Exit Sub
Set found = .Range("J5:J" & finalRow).Find(productname)
End With
If Not found Is Nothing Then
ThisWorkbook.Worksheets("Sheet1").Range("H3").Value = "Mobile Phone"
End If
End Sub