模块内代码

    1. Option Private Module
    2. Public strPath As String
    3. Sub GetFiles()
    4. Dim strFileName As String, k As Long
    5. With Application.FileDialog(msoFileDialogFolderPicker)
    6. '用户选择文件夹路径
    7. If .Show Then strPath = .SelectedItems(1) Else Exit Sub
    8. '如果用户未选择文件夹则退出程序
    9. End With
    10. If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
    11. Application.ScreenUpdating = False '取消屏幕刷新
    12. strFileName = Dir(strPath & "*.*")
    13. Cells(1, 1) = "目录": Cells(1, 2) = strPath
    14. Cells(2, 1) = "原名称": Cells(2, 2) = "新名称"
    15. k = 2 '清除当前工作表A列数据
    16. Do While strFileName <> ""
    17. k = k + 1
    18. Cells(k, 1) = strFileName
    19. strFileName = Dir
    20. '第2次调用Dir函数,未使用任何参数,则同目录下的下一个文件名
    21. Loop
    22. End Sub
    23. Sub 重命名()
    24. Dim k As Integer
    25. k = 3
    26. Do While Cells(k, 1) <> ""
    27. If Cells(k, 2) <> "" Then Name strPath & Cells(k, 1) As strPath & Cells(k, 2)
    28. k = k + 1
    29. Loop
    30. End Sub

    窗体内代码(两个按钮)

    1. Public sheet_name
    2. Private Sub CommandButton1_Click()
    3. Sheets.Add
    4. sheet_name = ActiveSheet.Name
    5. ActiveSheet.Columns("A:A").ColumnWidth = 20
    6. Call GetFiles
    7. CommandButton2.Enabled = True
    8. End Sub
    9. Private Sub CommandButton2_Click()
    10. Sheets(sheet_name).Activate
    11. Call 重命名
    12. Sheets(sheet_name).Delete
    13. End Sub
    14. Private Sub UserForm_Activate()
    15. CommandButton2.Enabled = False
    16. End Sub

    代码是“勉强能用”,这里的无窗口是说没有列表框或者表格之类的。嗯,根据这个的性质,至少需要两个宏。为了避免不熟悉功能误用的话,还是得需要一个窗口。
    他下一步的改造可以说是两个方向,第1个方向是把所有的模块都移动到窗口里面,把窗口的功能做得完备一点,并且修复一些bug。第2个方向是完全的无窗口化,依靠几个宏来分阶段完成功能。但代码会脆弱一些。容易错误使用。