【问题标题】:Excel vba save as using original file formatExcel vba另存为使用原始文件格式
【发布时间】:2014-04-24 16:17:43
【问题描述】:

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

【问题讨论】:

  • 到目前为止你尝试过什么?最坏的情况是 basic 字符串连接。显示您的代码,解释它在哪里没有按照您的意愿执行,我们很乐意为您提供帮助...
  • blogs.office.com/2009/07/07/… - 应该给你你想要的东西
  • 我尝试使用特定的文件格式#s,但显然,它们保存为指示的格式。我找到了对 xlNormal 的引用,但它始终保存为 xls。这是我尝试使用的代码:ActiveWorkbook.SaveAs _ FileName:=OutputPath & NewName, _ FileFormat:=xlNormal, _ Password:="", _ WriteResPassword:="", _ ReadOnlyRecommended:=False, _ CreateBackup: =假
  • 你试过链接里的代码了吗??

标签: vba excel


【解决方案1】:

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

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

可以在你的代码中使用:

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

我假设:

  • OutputPath 以“\”结尾
  • 文件名没有扩展名或尾随句点

【讨论】:

    【解决方案2】:

    您对问题的了解实际上已经使字符串处理(如@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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 2018-05-07
      • 2012-10-12
      • 1970-01-01
      相关资源
      最近更新 更多