Excel vba另存为原始文件格式

时间:2014-04-24 16:17:44

标签: excel vba excel-vba

我正在编写一个宏,它将打开模板工作簿,进行一些更改然后另存为新名称。有时模板工作簿将是xls,有时是xlsx。我使用什么作为fileformat参数,以便使用与原始模板文件相同的文件格式保存新文件?我看到的示例都使用特定的文件格式,在我的情况下可能会有所不同,具体取决于原始文件格式。我正在使用Excel 2010。

2 个答案:

答案 0 :(得分:0)

你对这个问题的了解已经实际上使@DavidZemens描述的字符串处理非常容易实现。以下是一个名为GetTheFileExtension的函数,它使用Workbook并返回string,其文件扩展名为Workbook

根据返回的If添加string语句来保存您的文件,您应该这样做:

Option Explicit
Public Function GetTheFileExtension(TargetWorkbook As Workbook) As String
    Dim sFullName As String, sTemp As String
    sFullName = TargetWorkbook.FullName '<~ grab the full file path
    sTemp = Right(sFullName, 4) '<~ we passed in a workbook, so only interested in the last 4
    If InStr(1, sTemp, ".", vbTextCompare) Then
        GetTheFileExtension = Right(sTemp, 3) '<~ if there's a period, we know it's .xls
    Else
        GetTheFileExtension = sTemp '<~ if not, we know it's xlsx
    End If
End Function

这是MsgBox扩展程序的一点点测试:

Sub TestThatFunction()

Dim sFileExtension As String

'test the function by assigning it to a string
sFileExtension = GetTheFileExtension(ThisWorkbook)

'msgbox to check the results
MsgBox (sFileExtension)

'add an If statement to your code
'that saves the file in one manner
'if the file extension is "xls"
'and in the other manner if the
'extension is "xlsx"

End Sub

答案 1 :(得分:0)

此函数将返回包含前导句点的文件扩展名。

Function FileExtension(Fname As String)
    FileExtension = Right(Fname, Len(Fname) - InStrRev(Fname, ".") + 1)
End Function

可以在您的代码中使用:

ActiveWorkbook.SaveAs FileName:=OutputPath & NewName & _
    FileExtension(ActiveWorkbook.Name)

我假设:

  • OutputPath以&#34; \&#34;
  • 结尾
  • FileName没有扩展名或尾随句号