Sub Macro1()
Dim Fso As Object, a, i&, j&, n&, brr()
Application.ScreenUpdating = False '关闭屏幕更新
Set Fso = CreateObject("Scripting.FileSystemObject") '创建FSO对象
p = ThisWorkbook.Path & "\2012-3-1" '当前路径下的文件夹
sFileType = "*.pdf" '类型为PDF文件
Call GetFiles(p, sFileType, Fso) '调用getfiles程序
ReDim brr(1 To m, 1 To 4) '定义二维数组
[a1].CurrentRegion.Offset(1).ClearContents 'a1所用区域整体向下清除内容
With ActiveSheet '以下激活的表内进行
For i = 1 To m 'i从1到m循环
a = Split(arr(i), "\") '将数组arr(i)用\分开写入数组a
n = 0
For j = UBound(a) - 3 To UBound(a) - 1 'j在数组a内的最后三个数循环
n = n + 1 'n自加一次
brr(i, n) = a(j) '为brr赋值
Next
brr(i, 4) = Replace(a(j), ".pdf", "") '删除.pdf
.Hyperlinks.Add Anchor:=Cells(i + 1, 4), Address:=arr(i) '建立超连接
Next
End With
[a2].Resize(m, 4) = brr '将数组brr赋到a2的扩展区域
m = 0
Erase arr '清除arr
Set Fso = Nothing '清除fso
Application.ScreenUpdating = True '开启屏幕更新
End Sub
Private Sub GetFiles(ByVal sPath$, ByVal sFileType$, Fso As Object)
Dim Folder As Object
Dim SubFolder As Object
Dim File As Object
Set Folder = Fso.GetFolder(sPath)
For Each File In Folder.Files '历遍spath下的文件
If File.Name Like sFileType Then '如文件名和sfiletype相仿
m = m + 1 'm自加
ReDim Preserve arr(1 To m) '重新定义数组arr,保留原有数据
arr(m) = sPath & "\" & File.Name '为数组的新增数据赋值
End If
Next
If Folder.SubFolders.Count > 0 Then '如果存在子文件夹
For Each SubFolder In Folder.SubFolders '历遍所有子文件夹
Call GetFiles(SubFolder.Path, sFileType, Fso) '再次运行些程序
Next
End If
Set Folder = Nothing
Set File = Nothing
Set SubFolder = Nothing
End Sub
VBA中的Cells语法是:Cells(行数,列数),行数和列数都是整数值,如:
cells(2,1)代表第二行第一列,也就是A2单元格,在VBA中,与Range("A2")所指一样.
cells(2,1)也可以写成cells(2,"A")
以此类推。
所以要在表格中的C4,D4,E4,F4 中输出要修改:
.Hyperlinks.Add Anchor:=Cells(4,i + 2), Address:=arr(i)