简体   繁体   English

从单元格功能中提取单词

[英]Extract words from cell function

I am using this function to extract a word from a cell. 我正在使用此功能从单元格中提取单词。

Function FindWord(Source As String, Position As Integer)
    Dim arr() As String

    arr = VBA.Split(Source, " ")
    xCount = UBound(arr)

    If xCount < 1 Or (Position - 1) > xCount Or Position < 0 Then
        FindWord = ""
    Else
        FindWord = arr(Position - 1)
    End If
End Function

I am looking for a way to extract multiple words instead of just one. 我正在寻找一种提取多个单词而不是一个单词的方法。

You can use a ParamArray parameter to specify any number of Position parameters. 您可以使用ParamArray参数指定任意数量的Position参数。

Something like this: 像这样:

Function FindWord(Source As String, ParamArray Position())
    Dim arr() As String
    Dim i As Long
    Dim xCount  As Long
    Dim ReturnString As String

    arr = VBA.Split(Source, " ")
    xCount = UBound(arr)

    For i = 0 To UBound(Position)
        If (Position(i) - 1) <= xCount And Position(i) > 0 Then
            ReturnString = ReturnString & " " & arr(Position(i) - 1)
        End If
    Next

    FindWord = Trim$(ReturnString)
End Function

then call it like 然后像

=FindWord(A1,3,2,1)

specifying as many Positions as desired 指定所需的位置

An option would be to use a Regexp to also validate that the strings were actually words. 一种选择是使用Regexp来验证字符串实际上是单词。

This function returns a 1D variant array that either returns 此函数返回一维变量数组,该数组要么返回

  • all valid strings if the optional positon sequence is not specified 如果未指定可选的位置序列,则所有有效字符串
  • the valid strings in the user specified order 用户指定顺序的有效字符串

Calling the function with 用调用函数
Y = GetWord("I am a test 109 sample", 4, 1)
Puts test in X(1) , I in X(2) 测试放在X(1) ,将I放在X(2)

在此处输入图片说明

test 测试

Sub TestCode()
Dim Y
Y = GetWord("I am a test 109 sample")
Y = GetWord("I am a test 109 sample", 4, 1)
End Sub

main 主要

Function GetWord(strIn As String, ParamArray Order()) As Variant
Dim objRegex As Object
Dim objRegexMC As Object
Dim objRegexM As Object
Dim X
Dim lngCnt As Long

Set objRegex = CreateObject("vbscript.regexp")

With objRegex
   .Pattern = "\b[a-z]+\b"
   .ignorecase = True
   .Global = True
If .test(strIn) Then
    Set objRegexMC = .Execute(strIn)
    If UBound(Order) < 0 Then
    'get all matches
    ReDim X(1 To objRegexMC.Count)
    For Each objRegexM In objRegexMC
        lngCnt = lngCnt + 1
        X(lngCnt) = objRegexM
    Next
    Else
    ReDim X(1 To UBound(Order()) + 1)
    For lngCnt = 1 To UBound(X)
        If Order(lngCnt - 1) <= objRegexMC.Count Then X(lngCnt) = objRegexMC(Order(lngCnt - 1) - 1)
Next        Next
    End If
GetWord = X
End If
End With
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM