比较两列 – VBA新手

我是新的Excel VBA,我想比较两列的单元格(string),并检查是否:

  • 有一些单元格有“两个”匹配的单词
  • 有一些细胞是由同一个词开始的

我的代码返回一个错误,我无法弄清楚,有人可以帮助我这个请!

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 

当我debugging时,突出显示的文本是:“如果compt> = 2或mot(0)= mot2(0)”。 由于我使用的是法语版本,所以翻译的错误是:“ 执行错误”9“:索引不属于select ”。

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 

试试这个,希望不要超过2个连续的空格:),把它写在分割之前

 x = Trim(Replace(x, " ", " ")) y = Trim(Replace(y, " ", " ")) 

使用此function删除不需要的空间:

 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)