[英]How to Match just part of a cell's value instead of an exact match in VBA for Excel?
[英]VBA Excel find exact value of a cell, not just part of it
我有以下代码:
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
将行Set User = AD_USERS.Range("D:D").Find(What:=wVal)
更改为
Set User = AD_USERS.Range("D:D").Find(What:=wVal, LookAt:=1)
当您使用后期绑定从单词 vba 创建和 excel 应用程序时,默认情况下未定义 excel 常量(例如xlWhole
)。 仅当您将 excel 引用添加到您的项目时才定义它们。 您可以使用Dim xlWhole As Integer: xlWhole = 1
自己定义它,或者在需要使用此常量时仅使用值1
。
正如@Foxfire And Burns And Burns 建议的那样,我最后使用了CountIf
,所以效果更好,我使用Find
解决了我的错误。 该行现在是:
User = AD_USERS.Application.WorksheetFunction.CountIf(AD_USERS.ActiveWorkbook.ActiveSheet.Range("D:D"), wVal)
谢谢大家的回答!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.