'跟你的示例结果有点差别,你确定是正确的吗?
Option Explicit
Sub test()
Dim arr, i, j, k, filename(), n, a, b, dic(1), t, key
For i = 0 To UBound(dic): Set dic(i) = CreateObject("scripting.dictionary"): Next
If Not getfilename(filename, ThisWorkbook.Path, ".xlsx") Then MsgBox "!": Exit Sub
ReDim arr(1 To UBound(filename))
a = 1: b = 2
For i = 1 To UBound(filename)
If filename(i) <> ThisWorkbook.FullName Then
n = n + 1
arr(n) = GetObject(filename(i)).Sheets("sheet1").[a1].CurrentRegion
For j = 2 To UBound(arr(n), 1)
t = arr(n)(j, 1) & arr(n)(j, 2)
If Not dic(0).exists(t) Then a = a + 1: dic(0)(t) = a
Next
For j = 3 To UBound(arr(n), 2)
If Not dic(1).exists(arr(n)(1, j)) Then b = b + 1: dic(1)(arr(n)(1, j)) = b
Next
End If
Next
ReDim brr(1 To dic(0).Count + 1, 1 To dic(1).Count + 2)
For i = 1 To n
For j = 2 To UBound(arr(i), 1)
t = arr(i)(j, 1) & arr(i)(j, 2)
brr(dic(0)(t), 1) = arr(i)(j, 1): brr(dic(0)(t), 2) = arr(i)(j, 2)
For k = 3 To UBound(arr(i), 2)
brr(dic(0)(t), dic(1)(arr(i)(1, k))) = arr(i)(j, k)
Next k, j, i
brr(1, 1) = "区域": brr(1, 2) = "名称": n = 2
For Each key In dic(1).keys: n = n + 1: brr(1, n) = key: Next
With Sheets("sheet1")
.Cells.ClearContents
.[a1].Resize(UBound(brr, 1), UBound(brr, 2)) = brr
End With
End Sub
Function getfilename(filename, pth, mark) As Boolean
Dim f, n
If Right(pth, 1) <> "\" Then pth = pth & "\"
f = Dir(pth & "*.*")
Do While Len(f) > 0
If LCase(Right(f, Len(mark))) = LCase(mark) Then
n = n + 1: ReDim Preserve filename(1 To n)
filename(n) = pth & f
End If
f = Dir
Loop
If n > 0 Then getfilename = True
End Function |