VBA-Excel /如何从字典中随机选取一个单词?

时间:2016-11-06 17:59:20

标签: excel vba excel-vba

假设我在Sheet2中有一个单词数据库;它从A1到B200。

我需要随机选择其中一个词;并在Sheet1中显示。

此外,我需要在单词的每个字母之间留有空格。

示例:随机选择的单词是COLD;它必须如下所示:

A1:C

A3:O

A5:L

A7:D

我该如何编码?

4 个答案:

答案 0 :(得分:2)

试试这段代码:

name[4]

答案 1 :(得分:0)

假设单词写在sheet2的A列中,您可以执行以下操作(此解决方案的一部分来自here

Sub randomWord()
Dim rndWordRow As Integer
Dim arr() As String
Dim buff() As String

'Select row between 1 and 200 randomly'
rndWordRow = Int((200 - 1 + 1) * Rnd + 1)

'Write text of the randomly selected row into variable'
rndWord = Sheets("Sheet2").Cells(rndWordRow, 1)

'Write letters of text into array'
ReDim buff(Len(rndWord) - 1)
For i = 1 To Len(rndWord)
    buff(i - 1) = Mid$(rndWord, i, 1)
Next

'Loop through array and write letters in single cells'
For i = 0 To UBound(buff)
    Sheets("Sheet1").Cells(i + 1, 1) = buff(i)
Next i

End Sub

答案 2 :(得分:0)

enter image description here

Sub Test()
    Dim x As Long
    Dim aWord
    With Worksheets("Sheet1")
        For x = 1 To 15
            aWord = getRandomWord
            .Cells(1, x).Resize(UBound(aWord)).value = aWord
        Next

    End With
End Sub

Function getRandomWord()
    Dim Source As Range
    Dim result
    Dim i As Integer
    Set Source = Worksheets("Sheet2").Range("A1:B200")

    i = Int((Rnd * Source.Cells.Count) + 1)
    result = StrConv(Source.Cells(i).Text, vbUnicode)
    result = Split(Left(result, Len(result) - 1), vbNullChar)
    getRandomWord = Application.Transpose(result)
End Function

答案 3 :(得分:0)

这是解决问题的简单方法。此例程为您提供两个字母之间的空白单元格,第一个单元格中包含第一个字母。

R1 = Int(Rnd() * 200)
R2 = Int(Rnd() * 2)

anyword = Sheet2.Cells(R1, R2)
x = Len(anyword)
n = -1: i = 1
Do
   n = n + 2
   Sheet1.Cells(n, 1) = Mid(anyword, i, 1)
   i = i + 1

Loop Until n > x * 2