从文本文件中读取,选择随机单词 [英] Read from text file, select random word

查看:175
本文介绍了从文本文件中读取,选择随机单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用VBA {Word 2003}将TXT文件{单词列表}读入变量列表,然后使用RND()从该列表中选择一个单词。我已经尝试了一些我通过谷歌发现的代码,虽然其中大部分都是针对Word VBA的更高版本,但没有任何效果,Office 2003是我喜欢的最后一个版本。



我偶尔会更改TXT文件,因此代码需要查看文件中有多少单词{每行一个单词}然后根据该数字执行RND()把这些词{通常是50到500字之间}放入变量列表。



我只是不知道从哪里去,并会感激任何帮助。



和平与你,

MatthewDra'GonStohler



我尝试过:



我通过Google找到的各种代码。

I want to use VBA {Word 2003} to read a TXT file {list of words} into a variable list then select a word from that list using RND(). I've tried a number of codes I've found via Google, though most of those were for later versions of Word VBA, but nothing has worked and Office 2003 is the last version that I like.

I would be changing the TXT file on occasion so the code would need to "see" how many words {one word per line} is in the file then do a RND() based on that number after putting the words {usually it would be between 50 to 500 words} into the variable list.

I just don't know where to go from here and would appreciate any help with this.

Peace to you and yours,
Matthew "Dra'Gon" Stohler

What I have tried:

Various codes I found via Google.

推荐答案

这很简单。请按照以下代码中的注释:



It's pretty easy. Please, follow the comment in below code:

Option Explicit

Sub Test()

'display message with random word
MsgBox GetRandomWordFromFile("D:\words.txt")

End Sub


Function GetRandomWordFromFile(ByVal sFileName As String) As String
    Dim sLine As String
    Dim iFile As Integer, iLine As Integer
    Dim words() As String 'array of words/string
    
    'variable to store no. of words
    iLine = 0
    'number of file
    iFile = FreeFile()
    Open sFileName For Input As #iFile
    Do Until EOF(iFile)
        'read line into variable
        Line Input #iFile, sLine
        'increase the size of array
        ReDim Preserve words(iLine)
        'word -> array
        words(iLine) = sLine
        'increase line no.
        iLine = iLine + 1
    Loop
    Close #iFile

    'count of words / lines
    iFile = UBound(words())
    
    'get random no.
    'Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
    iLine = Int((iFile - 1 + 1) * Rnd + 1)
    
    'return random word
    GetRandomWordFromFile = words(iLine)

End Function





祝你好运!



Good luck!


这篇关于从文本文件中读取,选择随机单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆