繁体   English   中英

比较两列 - VBA新手

[英]Comparing two columns - New to VBA

我是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

试试这个,并希望连续两个空格不超过:),在分割之前写下来

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM