首页 > 解决方案 > VBA Excel找到一个单元格的确切值,而不仅仅是它的一部分

问题描述

我有以下代码:

Set User = AD_USERS.Range("D:D").Find(What:=wVal)

wVal 是我正在寻找的值。它是用户名,可以是“Ecr484348”或“gh8644”。我的问题是,当我在查找用户名时,如何使用 find 来查找完全巧合?

我知道如果我使用xlWhole它看起来完全是巧合,但如果wVal = "Ecr"它会给我它找到“Ecr484348”,我不想要那个。我希望只有当你确实wVal = "Ecr484348"给你它找到了价值时,我的意思是我不希望它只使用用户名的某些部分来工作。

对不起,如果有什么没有很好的解释,我会回答如果有任何问题。非常感谢您的回答!

PS:如果我xlWhole在下面的代码中使用:

Set User = AD_USERS.Range("D:D").Find(What:=wVal, LookAt:=xlWhole)

它给我一个错误9,我不知道为什么。

PS2:我在这里添加整个代码:

Dim wrdTbl As Table
    'Set the Word table
    With ActiveDocument
        If ActiveDocument.Tables.Count >= 1 Then
            Set wrdTbl = .Tables(InputBox("Table # to copy? There are " & .Tables.Count & " tables to choose from."))
        End If
    End With

    Dim AD_UsersPath As String
    AD_UsersPath = "C:\Users\" & Environ("Username") & "\Desktop\Comparar Columnas VBA\Animales.xlsx"
    Dim AD_USERS As Object
    Set AD_USERS = CreateObject("Excel.Application")
    AD_USERS.Visible = False
    AD_USERS.Application.Workbooks.Open AD_UsersPath
    
    Dim LastRow As Integer
    LastRow = wrdTbl.Columns(1).Cells.Count 

    Dim I As Integer
    For I = 1 To LastRow
        wVal = wrdTbl.Cell(I + 1, 1)
        wVal = Left(wVal, Len(wVal) - 2) 
        Set User = AD_USERS.Range("D:D").Find(What:=wVal)
        If User Is Nothing Then
            wrdTbl.Cell(I + 1, 1).Shading.BackgroundPatternColor = wdColorRed 
        Else
            wrdTbl.Cell(I + 1, 1).Shading.BackgroundPatternColor = wdColorWhite 
        End If
    Next I
    
    AD_USERS.Quit
    Set AD_USERS = Nothing

标签: excelvbafind

解决方案


将行更改Set User = AD_USERS.Range("D:D").Find(What:=wVal)

Set User = AD_USERS.Range("D:D").Find(What:=wVal, LookAt:=1)

当您使用后期绑定从 word vba 创建和 excel 应用程序时,xlWhole默认情况下不定义 excel 常量(例如 )。仅当您将 excel 引用添加到项目时才定义它们。您可以自己定义它,也可以在需要使用此常量时Dim xlWhole As Integer: xlWhole = 1仅使用该值。1


推荐阅读