我在开发包含部分匹配功能的for循环时遇到问题。
要解决该问题:
我要比较两张纸-一张纸存在于sheet1列b,另一张存在于sheet2列c。
for循环将遍历Sheet1上的B列,然后在每一行提取当前字符串-然后将该当前字符串传递给我尝试了vlookup ,并将其与表单2上的ENTIRE列C进行比较,找到一个匹配项:如果存在匹配项,它将返回C列右侧的ADJACENT列,然后将该值存入B列右侧的ADJACENT列。
我目前正在尝试执行一个for语句,该语句遍历Column b,并且如果B的当前字符串等于Column C的Vlookup以匹配Current字符串,则返回该值。
Sub JoinGroupOnPN()
Dim PartGroupSheet As Worksheet
Dim OEEPartSheet As Worksheet
Dim OEERowRange As Long
Dim OEEColumnRange As Long
Dim PGRowRange As Long
Dim PGColumnRange As Long
Dim OEEArray As Variant
Dim PGArray As Variant
Dim i As Long, j As Long
Set PartGroupSheet = ActiveWorkbook.Worksheets("PartGroup")
Set OEEPartSheet = ActiveWorkbook.Worksheets("OEE Report")
OEERowRange = OEEPartSheet.Cells(Rows.Count, 1).End(xlUp).Row
OEEColumnRange = OEEPartSheet.Cells(1,Columns.Count).End(xlToLeft).Row
PGRowRange = PartGroupSheet.Cells(Columns.Count, 1).End(xlUp).Row
PGColumnRange = PartGroupSheet.Cells(1,Columns.Count).End(xlToLeft).Row
ReDim OEEArray(OEERowRange, OEEColumnRange)
ReDim PGArray(PGRowRange, PGColumnRange)
Dim StringToMatch As String
Dim MatchingString As String
For i = 2 To OEERowRange
StringToMatch = OEEPartSheet.Cells(i, 1).Text
MatchingString = Application.WorksheetFunction.VLookup(Arg1:=StringToMatch, Arg2:=PartGroupSheet.Range(Cell1:=2, Cell2:=1), Arg3:=2, Arg4:=True)
For j = 2 To PGRowRange
If StringToMatch = MatchingString Then
Debug.Print StringToMatch
End If
Next j
Next i
End Sub
我不断收到错误消息,指出范围对象失败,并且我尝试将其转换为范围类型,但仍然是相同的错误。
错误发生在
MatchingString = Application.WorksheetFunction.VLookup(Arg1:=StringToMatch, Arg2:=PartGroupSheet.Range(Cell1:=2, Cell2:=1), Arg3:=2, Arg4:=True)
,错误消息是“对象” _WorkSheet的方法“范围”失败
我还不能发布任何图片
任何帮助将不胜感激,谢谢!!
答案 0 :(得分:1)
类似的事情应该起作用:
Sub JoinGroupOnPN()
Dim PartGroupSheet As Worksheet
Dim v, c As Range, rngSrch As Range
Set PartGroupSheet = ActiveWorkbook.Worksheets("PartGroup")
With ActiveWorkbook.Worksheets("OEE Report")
Set rngSrch = .Range(.Range("B2"), .Cells(.Rows.Count, "B").End(xlUp))
End With
For Each c In rngSrch.Cells
If Len(c.Value) > 0 Then
'do not use WorksheetFunction here
v = Application.VLookup(c.Value, PartGroupSheet.Range("B:C"), 2, False)
c.Offset(0, 1).Value = IIf(IsError(v), "No match", v)
End If
Next c
End Sub