有哪个VB高手帮忙编一个程序

2025-01-25 02:32:56
推荐回答(3个)
回答1:

Private TxtName() As String '定义一个数组装入txt名称
Sub GetTxtName(ByVal sPath As String, ByVal Filter As String) '这是获取指定文件夹下指定后缀名的文件名称的过程,装入数组txtname()中,spath就是这里写放txt的文件夹路径
Dim sDir As String
Dim sFilter() As String
Dim lngFilterIndex As Long
Dim lngIndex As Long
sFilter = Split(Filter, ",")
If Right(sPath, 1) <> "\" Then sPath = sPath & "\"
For lngFilterIndex = LBound(sFilter) To UBound(sFilter)
sDir = Dir(sPath & sFilter(lngFilterIndex))
Do While Len(sDir) > 0
lngfiles = lngfiles + 1
ReDim Preserve TxtName(1 To lngfiles)
TxtName(lngfiles) = sDir
sDir = Dir
Loop
Next
End Sub

'这是以前写的一段代码拿来用用,接下来只要随机一下数组下标,就能达到随机打开的目的
Sub RndOpen(sPath As String)
Dim i%
If Right(sPath, 1) <> "\" Then sPath = sPath & "\"

Randomize
i = Int(Rnd() * UBound(TxtName)) + 1
Shell "notepad.exe " & sPath & TxtName(i), vbNormalFocus
End Sub

Private Sub Command1_Click() '调用示例
Dim sPath As String
sPath = "c:\1\"
Call GetTxtName(sPath, "*.txt")
Call RndOpen(sPath)
End Sub

回答2:

mijing2000 的这个过程不错,比以前我写的遍历文件夹来得更实在,不过有些地方可以省略掉,如果文件过多的话,会浪费时间.

Sub GetTxtName(ByVal sPath As String, ByVal Filter As String)
Dim sDir As String
Dim Lngfiles As Long
'''Dim sFilter() As String '可略
'''Dim lngFilterIndex As Long ‘可略
'''Dim lngIndex As Long ‘可略
'''sFilter = Split(Filter, ",") ‘可略

If Right(sPath, 1) <> "\" Then sPath = sPath & "\"
'''For lngFilterIndex = LBound(sFilter) To UBound(sFilter) ‘可略

sDir = Dir(sPath & Filter) '''sFilter(lngFilterIndex)) ‘可略

Do While Len(sDir) > 0
Lngfiles = Lngfiles + 1
ReDim Preserve TxtName(1 To Lngfiles)
TxtName(Lngfiles) = sDir
sDir = Dir
Loop
'''''Next
End Sub

回答3:

方法一、可用DIR函数将文件名读入到一个数组中
方法二、使用File控件,添加一个File控件、一个ListBox控件,将这俩控件的visible设为false即不可见:
Private Sub Form_Load()
For i = 0 To File1.ListCount - 1
If LCase(Right(File1.List(i), 4)) = ".txt" Then List1.AddItem File1.List(i)
Next
End Sub
Private Sub Command1_Click()
Randomize
Shell "notepad.exe " & List1.List(Int(List1.ListCount * Rnd)), vbNormalFocus
End Sub
此程序需要在你的txt文件所在文件夹中运行。