我正在尝试编写一些VBA代码,它将在sheet2上的A列中的唯一值列表中取第一个值,并根据sheet1上A列中的唯一值进行搜索。一旦找到,它将更新sheet1上活动单元格右侧的单元格6,其值与sheet2中的唯一代码相邻。它将继续运行,在sheet2中运行列表的其余部分,直到它到达空白单元格。
我设法获取代码以找到唯一值,然后通过添加1来更新单元格6,但我无法解决其他问题:
Private Sub SinglePaste_Click()
On Error GoTo InvalidBarcode
Dim EAN As Range
Sheets("Paste Here").Select
For Each EAN In ActiveSheet.Range("A:A")
Sheets("Master Stock File").Select
With Worksheets("Master Stock File")
.Range("A:A").Find(What:=EAN, After:=.Range("A1"), LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False).Activate
ActiveCell.Offset(0, 6).Select
ActiveCell.Value = ActiveCell.Value + 1
End With
If IsEmpty(EAN) Then Exit For
Next EAN
Exit Sub
InvalidBarcode:
MsgBox ("Invalid Barcode - " & "" & EAN)
End Sub
这有意义吗?非常感谢任何帮助。
答案 0 :(得分:1)
您的代码使用大量ActiveSheet,ActiveCell和Select来指示宏录制器,效率通常较低。我仍然不确定你提到的“另一位”是什么,但这是一个重做的宏:
Public Sub NewSinglePaste_Click()
Dim EAN As Range
Dim FoundRange As Range
Dim ValueCell As Range
Dim MasterSheet As Worksheet
Dim PasteSheet As Worksheet
Set MasterSheet = Sheets("Master Stock File")
Set PasteSheet = Sheets("Paste Here")
On Error GoTo InvalidBarcode
For Each EAN In PasteSheet.Range("A:A")
If IsEmpty(EAN.Text) Or EAN.Text = "" Then Exit For
Set FoundRange = MasterSheet.Range("A:A").Find(What:=EAN, _
After:=MasterSheet.Range("A1"), LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If Not (FoundRange Is Nothing) Then
Set ValueCell = FoundRange.Offset(0, 6)
ValueCell.Value = ValueCell.Value + 1
Else
Debug.Print "Cell not found: " & EAN.Worksheet.Name & "!" & EAN.Address
End If
Next EAN
Exit Sub
InvalidBarcode:
MsgBox ("Invalid Barcode - " & "" & EAN)
End Sub