如何从单元格中查找单个值

问题描述 投票:0回答:1

Cell的值范围用逗号分隔。如何从该单元格中找到单个值? 以下代码无效

Public Sub Search_ChangeInitiator()

    Dim Company As String

      Company = GazelleValidation1.Company2.Value

      Company = Replace(Company, "AZ ", " ")
      Company = Replace(Company, "EXT ", " ")
      Company = Replace(Company, "AZB EXT ", " ")

      Company = Trim(Company)

      Dim sh As Worksheet
      Set sh = ThisWorkbook.Sheets("Validate")
      Dim ans As Range

         Dim InitiatorValue As Range

         Set InitiatorValue = Worksheet("Validate").Range("H2").Select

   Set ans = InitiatorValue.Find(what:=Company, MatchCase:=False, SearchFormat:=False)

    If ans Is Nothing Then
        Gazellevalidation2.Pchnageinitiator.Value = "Not Added"
    Else
        Gazellevalidation2.Pchnageinitiator.Value = "Added"
    End If
End Sub
vba excel-vba excel
1个回答
0
投票

如果您的文本被分隔符(在本例中为逗号)拆分为项目,则可以使用Split将其转换为数组:

Sub TestingTheSplitFunction()
    Dim ValueArray() As String 'Create an array variable
    ValueArray = Split("A,B,C,D", ",") 'Populate it with the items in your list (here "A", "B", "C" and "D")

    'Everything except the last line is just to make the example more visual
    Dim lReturn As Long, sTest As String
    sTest = "X"

    While Not IsNumeric(sTest)
        sTest = InputBox("Which item in the list would you like to retrieve?", Default:="1")
        If sTest = "" Then Exit Sub 'If you click cancel then stop.
    Wend 'Keep trying until we get a number or Cancel
    lReturn = CLng(sTest) + LBound(ValueArray) - 1 'If the Array starts at 0 then the first item is at position 0

    If lReturn < LBound(ValueArray) Then '0 or negative
        MsgBox "That's not a real position", vbCritical
    ElseIf lReturn > UBound(ValueArray) Then 'Larget than list size
        MsgBox "There are not that many items in the list!", vbCritical
    Else
        MsgBox ValueArray(lReturn) 'Tells you the value
    End If

    Erase ValueArray 'Free up the Array Memory
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.