【VBA】批量转化表格格式(xls转xlsx、csv转xlsx)

VBA—批量转化表格格式(xls转xlsx、csv转xlsx)

Excel可以通过另存为方式改变表格格式,如果遇到大批表格需要转化格式,手动另存为效率尤其慢。
我们可以使用VBA批量转化表格格式。

分享两种常用的表格格式转化:

一、xls转xlsx

把所有需要转化的报表放在同一个文件下,打开表格—复制以下代码即可。

'***********访问当前文件夹下所有子文件夹及文件, Dim iFile(1 To 100000) As String Dim count As Integer Sub xls2xlsx() iPath = ThisWorkbook.Path On Error Resume Next count = 0 zdir iPath For i = 1 To count If iFile(i) Like "*.xls" And iFile(i) <> ThisWorkbook.FullName Then MyFile = iFile(i) FilePath = Replace(MyFile, ".xls", ".xlsx") If Dir(FilePath, 16) = Empty Then Set WBookOther = Workbooks.Open(MyFile) Application.ScreenUpdating = False ActiveWorkbook.SaveAs Filename:=FilePath, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False WBookOther.Close SaveChanges:=False '解决不能close 文件问题
                Application.ScreenUpdating = True
            End If
            Kill myfile  '删除原xls文件 End If Next End Sub Sub zdir(p) '访问当前文件夹下所有子文件夹及文件
  Set fs = CreateObject("scripting.filesystemobject")
  For Each f In fs.GetFolder(p).Files
    If f <> ThisWorkbook.FullName Then count = count + 1: iFile(count) = f
  Next
  For Each m In fs.GetFolder(p).SubFolders
      zdir m
  Next
End Sub

二、csv转xlsx

同上面的代码,只是将xls改为csv。

'***********访问当前文件夹下所有子文件夹及文件, Dim iFile(1 To 100000) As String Dim count As Integer Sub xls2xlsx() iPath = ThisWorkbook.Path On Error Resume Next count = 0 zdir iPath For i = 1 To count If iFile(i) Like "*.csv" And iFile(i) <> ThisWorkbook.FullName Then myfile = iFile(i) FilePath = Replace(myfile, ".csv", ".xlsx") If Dir(FilePath, 16) = Empty Then Set WBookOther = Workbooks.Open(myfile) Application.ScreenUpdating = False ActiveWorkbook.SaveAs Filename:=FilePath, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False WBookOther.Close SaveChanges:=False '解决不能close 文件问题
                Application.ScreenUpdating = True
            End If
            Kill myfile  '删除原csv文件 End If Next End Sub Sub zdir(p) '访问当前文件夹下所有子文件夹及文件
  Set fs = CreateObject("scripting.filesystemobject")
  For Each f In fs.GetFolder(p).Files
    If f <> ThisWorkbook.FullName Then count = count + 1: iFile(count) = f
  Next
  For Each m In fs.GetFolder(p).SubFolders
      zdir m
  Next
End Sub
    原文作者:莫里_Katie
    原文地址: https://blog.csdn.net/weixin_47313201/article/details/110239210
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞