【发布时间】:2021-08-18 04:31:43
【问题描述】:
我有 4 组标准要匹配。 如果要从 sheet1.range("A1:J1") 检查的范围数据包含:10 种水果。 我想知道哪个组与范围数据的匹配度最高。
例如:enter image description here
我尝试了以下代码,但不起作用:
Sub Get_the_relevant_group()
Dim wb As Workbook
Dim sh As Worksheet
Dim searchList As Variant
Dim searchVal As Variant, val2check As Variant
Dim rng2check As Range
Dim cell2check As Range
Dim iMatch As Integer
Set wb = ActiveWorkbook
Set sh = wb.ActiveSheet
iCol = sh.Cells(1, Columns.Count).End(xlToLeft).Column
Set rng2check = sh.Range(sh.Cells(1, 1), sh.Cells(1, iCol))
GroupA = Array("Apple", "Banana", "Coconut", "Grape", "Orange", "Guava", "Durian", _
"Blackcurrent", "Mango", "Strawberry")
GroupB = Array("Apple", "Coconut", "Guava", "Mango", "Strawberry", "Lime", "Grape", "Pear", "Blueberry", "Lemon")
GroupC = Array("Apple", "Grape", "Durian", "Pineapple", "Watermelon", "Blueberry", "Banana", "Lemon")
GroupD = Array("Apple", "Orange", "Lime", "Plums", "Pear", "Lemon", "Coconut", "Grape")
For iGroup = 1 To 4
If iGroup = 1 Then searchList = GroupA
If iGroup = 2 Then searchList = GroupB
If iGroup = 3 Then searchList = GroupC
If iGroup = 4 Then searchList = GroupD
For Each cell2check In rng2check
If cell2check <> "" Then
For Each searchVal In searchList
val2check = cell2check.Value
If InStr(1, val2check, searchVal) > 0 Then
iMatch = iMatch + 1
Exit For
End If
Next searchVal
End If
If iMatch = iCol Then Exit For
Next cell2check
Next iGroup
End Sub
我希望有人能给我解决方案。非常感谢
【问题讨论】:
-
使用
Option Explicit强制声明所有变量(例如Dim iCol As Long,...)。在For iGroup = 1 To 4之后添加行iMatch = 0,在Next cell2check之后添加行Debug.Print "Group" & iGroup & " Total = " & iMatch。现在您可以在立即窗口 (Ctrl+G) 中看到一些结果。请分享您期望代码执行的操作,例如:是否应该是Sub并执行某项操作,是否应为Function并返回某些内容...