我是Excel VBA的新手,我想比较两列的单元格(字符串)并检查是否:
我的代码返回错误,我无法弄明白,有人可以帮我解决这个问题!
Sub Find_Matches()
Dim CompareRange As Variant, x As Variant, y As Variant, mot As Variant, mot2 As Variant, compt As Variant, element As Variant, element2 As Variant
compt = 0 'counter for number of matching words
Set CompareRange = Range("C1:C1796") 'first column
For Each x In Selection 'second column
For Each y In CompareRange
mot = Split(x, " ") 'converting strings to words arrays
mot2 = Split(y, " ")
For Each element In mot
For Each element2 In mot2
If element = element2 Then compt = compt + 1 'matching words counter incrementation
Next element2
Next element
If compt >= 2 Or mot(0) = mot2(0) Then .... 'if/or then do something
compt = 0
Next y
Next x
End Sub
当我调试时,突出显示的文字是:“如果compt> = 2或mot(0)= mot2(0)”。我使用法语版本时翻译的错误是:“执行错误'9':索引不属于选择”。
UPDATE1:即使单元格不为空,我仍然有相同的错误,同一行上的错误相同:
For Each x In Selection
For Each y In CompareRange
If CStr(x) & CStr(y) <> vbNullString Then
mot = Split(x, " ")
mot2 = Split(y, " ")
Else: MsgBox "empty cell!"
End If
For Each element In mot
For Each element2 In mot2
If element = element2 Then compt = compt + 1
Next element2
Next element
If compt >= 2 Or mot(0) = mot2(0) Then x.Offset(0, 1) = x
compt = 0
Next y
Next x
答案 0 :(得分:2)
试试这个,希望连续的空格不超过2个:),在分割之前写一下
x = Trim(Replace(x, " ", " "))
y = Trim(Replace(y, " ", " "))
使用此功能删除不需要的空格:
Function RemoveSpaces(ByVal s As String) As String
Dim a As Integer, b As Integer
s = Trim(s)
Do
a = Len(s)
s = Replace(s, " ", " ")
b = Len(s)
Loop Until a = b
RemoveSpaces = s
End Function
现在你的子使用x = RemoveSpaces(x)