我正在尝试编写一个宏来打开文件夹中的每个文件,然后保存为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完全不熟悉所以任何帮助都会非常感激。 谢谢
答案 0 :(得分: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
答案 1 :(得分:0)
您当前的代码仅查找已具有.xlsx扩展名的文件。试试Dir('*')
。
如果您只是重命名文件,那么我不会尝试打开它们。我会使用FileCopy
FileCopy source, destination
其中source和destination都是字符串。例如,以下内容适用于我(在Windows XP上):
FileCopy "testthis", "testthis.xlsx"
然后,您可以使用Kill
删除旧文件
Kill pathname