我可以用Excel函数从句子中产生一个随机单词吗?

任何人都可以显示一个函数来从Excel中的句子中获取一个随机单词。 我正在做一个差距填充练习。 列A1包含长句子列表(每个句子在一行上)。 我需要从A1的每个句子中获得列B1包含列表或随机单词。 我一直在寻找相当长的一段时间,但还没有find任何可能的。 另外,如果可以在Excel中完成,速度比其他方式快。 我认为。

本页面显示如何使用excel vba从给定句子中提取第n个单词。 该函数被命名为“FindWord”。 使用另一个函数“CountWord”来计算句子中的单词,然后使用这两个单词的组合如下

=FindWord(A1,RANDBETWEEN(1,CountWord(A1))) 

(单元格A1包含要从中提取单词的句子)

以下是function代码(按Alt + F11,转到插入>>模块,然后将以下代码粘贴到模块中)

 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 '''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''' Function CountWord(Source As String) Dim arr1() As String arr1 = VBA.Split(Source, " ") x1count = UBound(arr1) CountWord = x1count + 1 End Function 

资料来源: http : //www.extendoffice.com/documents/excel/1336-excel-extract-first-last-nth-word.html

这是我的自定义function,增加了一些额外的function。

Public Function GetRandomWords(TheCell As Range, Optional AllowDuplicates As Boolean, Optional NumberOfWords As Integer, Optional Delimiter As String) As String

基本上,它将从单元格中获得一个随机的单词数量(在1和单元格中的最大单词数量之间)。

默认情况下,它不允许重复,会得到一个随机数字,并使用Excel的默认分隔符。

您可以更改随机词语的数量,分隔符,是否允许重复。

您可以使用CTRL + ALT + SHIFT + F9重新计算公式

您可以通过使用CTRL + SHIFT + A键入公式中显示参数

 Public Function GetRandomWords(TheCell As Range, Optional AllowDuplicates As Boolean, Optional NumberOfWords As Integer, Optional Delimiter As String) As String If TheCell.CountLarge > 1 Then Set TheCell = TheCell.Cells(1, 1) Dim Words() As String Dim NixDupe As New Collection Dim Helper As Integer Dim Final As String Dim x As Integer If Delimiter = "" Then Words = Split(TheCell.Value) Else Words = Split(TheCell.Value, Delimiter:=Delimiter) End If For x = 0 To UBound(Words) NixDupe.Add Words(x) Next x If NumberOfWords = 0 Then NumberOfWords = Int((NixDupe.Count) * Rnd + 1) End If If (NumberOfWords > NixDupe.Count And Not AllowDuplicates) Or NumberOfWords < 0 Then NumberOfWords = NixDupe.Count Final = "" For x = 1 To NumberOfWords Helper = Int((NixDupe.Count) * Rnd + 1) Final = Final & NixDupe(Helper) & " " If Not AllowDuplicates Then NixDupe.Remove (Helper) If NixDupe.Count = 0 Then Exit For End If Next x GetRandomWords = Trim(Final) End Function 

使用=GetRandomWords(A1)

RandomWords

使用=GetRandomWords(A1,FALSE,3)

RandomWords2

还有一个使用绝对单元格引用的不同语句。

=GetRandomWords($A$1,FALSE,1)

RandomWords3

使用一个熟悉的方法来计算一个短语中的单词来设置一个RANDBETWEEN函数的上边界应该让你开始parsing出一个随机的单词。

random_words

B1中的公式是,

 =TRIM(MID(SUBSTITUTE(" "&A1, " ", REPT(" ", LEN(A1))), RANDBETWEEN(1, LEN(A1)-LEN(SUBSTITUTE(A1, " ", ""))+1)*LEN(A1), LEN(A1))) 

根据需要填写。 您可能希望在parsing随机单词之前删除逗号和句点。