1

我正在尝试编写一个宏来打开文件夹中的每个文件,然后将其保存为 xlsx 文件。我正在使用的文件没有文件扩展名,数据是制表符分隔的,可以手动打开。我有这段代码可以打开文件夹中的每个文件,但是我无法让它打开没有文件扩展名的文件。

Sub Open_All_Files()
Dim oWbk As Workbook
Dim sFil As String
Dim sPath As String

sPath = "E:\Macro" 'location of files
ChDir sPath
sFil = Dir("*.xlsx") 'change or add formats
Do While sFil <> "" 
Set oWbk = Workbooks.Open(sPath & "\" & sFil) 'opens the file

'Code to save as different file extension would go here

oWbk.Close True 'close the workbook, saving changes
sFil = Dir
Loop ' End of LOOP
End Sub

我也不知道如何让每个文件保存为 xlsx 文件。

我对 vba 完全陌生,因此将不胜感激任何帮助。谢谢

4

2 回答 2

1

我知道这是您要查找的代码:

Sub Open_All_Files()
   Dim oWbk As Workbook
   Dim sFil As String
   Dim sPath As String

   sPath = "E:\Macro" 'location of files
   ChDrive "E" '-> if E is different than the current drive (if you didn't change it before, it is the drive where Office is installed)
   ChDir sPath
   sFil = Dir("*.*") 'change or add formats
   Do While (sFil <> ""  And InStr(sFil, ".") = 0)
      NewFileName = sPath & "\" & sFil & ".xlsx"

      On Error Resume Next
      Name sFil As NewFileName 'Add extension to file

      Set oWbk = Workbooks.Open(NewFileName) 'Open file as XLSX

      'Do anything with the workbook

      oWbk.Close True 'close the workbook, saving changes

      sFil = Dir("*.*")
   Loop ' End of LOOP
End Sub
于 2013-06-26T11:17:10.820 回答
0

您当前的代码仅查找已具有 .xlsx 扩展名的文件。试试Dir('*')

如果您只是重命名文件,那么我不会尝试打开它们。我会用FileCopy

FileCopy source, destination

其中源和目标都是字符串。例如,以下对我有用(在 Windows XP 上):

    FileCopy "testthis", "testthis.xlsx"

然后您可以使用Kill删除旧文件

Kill pathname
于 2013-06-26T11:14:24.527 回答