vba - 比较vba excel中的两个字符串

标签 vba excel compare string-comparison

我需要将“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

但它给了我这个结果:

http://i.stack.imgur.com/iiPLe.jpg

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

最佳答案

问题出在 InStr功能-> https://msdn.microsoft.com/en-us/library/8460tsh1%28v=vs.90%29.aspx
Temps = InStr(1, UCase(Nom), UCase(Nomchercher), vbTextCompare)
您搜索 UCase(Nomchercher)UCase(Nom)
你总能找到 Nom = ""Nomchercher 列的所有数据中

这将更好地工作:
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

关于vba - 比较vba excel中的两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30737170/

相关文章:

excel - 使用 vba-excel 从共享点下载整个目录(文件夹)

vba - 使用 Excel VBA 根据每个单元格中的值自动设置行格式?

ruby-on-rails - 如何比较Yaml文件中的键?

Excel 无法正确打开没有 .csv 扩展名的 csv 文件

mysql - 比较 mysql 中的最后 10 个字符?

perl - 我应该如何比较 Perl 引用文献?

c++ - 如何在 VS2010 C++ 宏中使用 DTE.ExecuteCommand ("Edit.GoToDefinition")?

Excel公式比较两个数组

excel - 使用 Excel VBA 命令删除除特定 ShapeType 之外的所有形状

c# - 用 OLEDB 读取 Excel 文件?