【问题标题】:Compare two strings in vba excel比较vba excel中的两个字符串
【发布时间】:2015-08-24 13:46:15
【问题描述】:

我需要将“Chef”列的每个单元格与“nom”列的每个单元格进行比较,以便找到正确的“matricule”并将其存储在“matt”中, 我试过这个 VBA 代码:

 Sub compare()
Dim p As Integer
    Dim q As Integer
    Dim Nom As String
    Dim Nomchercher As String
    Dim Matr As String

    p = 0
    q = 0

    For j = 1 To 10
        p = p + 1
        Cells.Find("Chef").Select
        ActiveCell.Range("a1").Offset(p, 0).Activate
        ActiveCell.Select
        AdresseTexte1 = ActiveCell.Address(0, 0)
        Nomchercher = Range(AdresseTexte1)

    For i = 1 To 10

        q = q + 1
        Cells.Find("Nom").Select
        ActiveCell.Range("a1").Offset(q, 0).Activate
        AdresseTexte2 = ActiveCell.Address(0, 0)
        Nom = UCase(Range(AdresseTexte2))
        Cells.Find("Matricule").Select
        ActiveCell.Range("a1").Offset(q, 0).Activate
        AdresseTexte3 = ActiveCell.Address(0, 0)
        Matr = UCase(Range(AdresseTexte3))



        Cells.Find("Matt").Select
        ActiveCell.Range("a1").Offset(p, 0).Activate
        Temps = InStr(1, UCase(Nom), UCase(Nomchercher), vbTextCompare)

       If Temps <> 0 Then
       ActiveCell.Value = Matr
       End If
    Next i
    q = 0
    Next j
End Sub

但它给了我这个结果:

我不知道为什么它显示“48”,有帮助吗?

【问题讨论】:

  • 你看过VLOOKUP吗?我怀疑你会得到48 的空白条目,因为没有匹配项,48 是你在循环中循环到的最后一个单元格......

标签: vba excel compare string-comparison


【解决方案1】:

问题出在InStr函数-> https://msdn.microsoft.com/en-us/library/8460tsh1%28v=vs.90%29.aspx

Temps = InStr(1, UCase(Nom), UCase(Nomchercher), vbTextCompare)

你在UCase(Nom)中搜索UCase(Nomchercher)

您总是在Nomchercher 列的所有数据中找到Nom = ""

这样会更好:

Temps = InStr(1, UCase(Nomchercher), UCase(Nom), vbTextCompare)

编辑:(更快的比较)

Sub FasterCompare()

Dim ColMatricule As Integer
Dim ColNom As Integer
Dim ColChef As Integer
Dim ColMatt As Integer
Dim LastRow As Long

ScreenUpdating = False

'find column name
ColMatricule = Cells.Find("Matricule").Column
ColNom = Cells.Find("Nom").Column
ColChef = Cells.Find("Chef").Column
ColMatt = Cells.Find("matt").Column

'find last row of data
LastRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

For j = 2 To LastRow 'chef
    If Cells(j, ColChef) <> vbNullString Then 'if chef is null then dont search nom
        For i = 2 To LastRow 'nom
            If Cells(j, ColChef) = Cells(i, ColNom) Then
            Cells(j, ColMatt) = Cells(i, ColMatricule)
            Exit For
            End If
        Next i
    End If
Next j

ScreenUpdating = True

End Sub

【讨论】:

  • 它在行数较少(或多或少 20 行)时工作,但是当我在包含 4615 行的实际文件中尝试它时,它没有,为什么?
  • 你只检查前 10 行 For j = 1 To 10 For i = 1 To 10 这可能是个问题
  • i 检查对于 j = 1 到 4615 对于 i = 1 到 4615
  • 每个“chef”对应的“matt”不是正确的“matricule”
  • 唯一让我想到的是,您的代码显示最后找到的Nom,您对错误的描述过于笼统。可以添加数据源吗,问题出现在哪里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多