|
本帖最后由 weiyingde 于 2017-8-26 14:59 编辑
要求从当前目录及以下所有子目录中的文件名(全名,即fullname)中随机抽取一个,可是名字并不随机,不知是问什么。
代码如下:
Sub 随机抽取文件名()
On Error Resume Next
Dim fn(1 To 10000) As String
Dim F, I, k, f2, x, 文件名$
Dim arr1(), arr2(), arr3(), crr(), q As Integer
t = Timer
fn(1) = ActiveDocument.Path & "\"
I = 1: k = 1
Do While I < UBound(fn)
If fn(I) = "" Then Exit Do
F = Dir(fn(I), vbDirectory) '
Do
If InStr(F, ".") = 0 And F <> "" Then
k = k + 1
fn(k) = fn(I) & F & "\"
End If
F = Dir
Loop Until F = ""
I = I + 1
Loop
'*******下面是提取各个文件夹的文件***
For x = 1 To UBound(fn)
If fn(x) = "" Then Exit For
f2 = Dir(fn(x) & "*.*")
Do While f2 <> ""
q = q + 1
ReDim Preserve arr1(1 To q)
ReDim Preserve arr2(1 To q)
ReDim Preserve arr3(1 To q)
arr1(q) = Left(f2, Len(f2) - 4)
arr2(q) = Right(f2, 3)
arr3(q) = fn(x) & f2
f2 = Dir
Loop
Next x
‘’改为 ReDim crr(1 To q, 1 To 3)
For j = 1 To q
ReDim Preserve crr(1 To j, 1 To 3) ‘或改为’ ReDim Preserve crr(1 To q, 1 To 3)
crr(j, 1) = arr1(j)
crr(j, 2) = arr2(j)
crr(j, 3) = arr3(j)
Next
Randomize
sj = Int(Rnd * q) + 1
文件名$ = crr(sj, 1)
With ActiveDocument
.Range(0, 0).InsertAfter vbCr & "第" & sj & "文件是:" & crr(sj, 3)
End With
End Sub
代码中,不管sj是多少,crr(sj, 3)始终是一个原名称,从不改变,不是为什么。
只有一维数组arr3(sj)是每次不同。难道不能从二维数组中随机取值吗?
|
|