使用vba name语句进行xls到xlsx的转换会破坏文件

时间:2013-04-03 23:29:37

标签: excel vba excel-vba rename corrupt

我正在尝试使用以下代码将文件从abcd.xls重命名为xyz.xlsx -

  NumOfAttachments = Range("RecCount").Value
  DestinationFolderPath = Range("destinationfolder").Value
  NewShtName = "Sheet1"

  If NumOfAttachments <> 0 Then
    For X = 0 To NumOfAttachments - 1
      OrigName = Range("Startcell").Offset(X, 1).Value
      NewName = Range("startcell").Offset(X, 2).Value
      SourceFolderPath = Range("startcell").Offset(X, 3).Value
      NewFile = DestinationFolderPath & NewName
      If Dir(DestinationFolderPath & OrigName) <> "" Then Kill DestinationFolderPath & OrigName
      FileCopy SourceFolderPath & OrigName, DestinationFolderPath & OrigName

      If Dir(NewFile) <> "" Then Kill NewFile
      Name DestinationFolderPath & OrigName As NewFile

此后,当我尝试打开文件(xyz.xlsx)时,出现以下错误 -

excel cannot open the file xyz.xlsx because the file format or file extension is not valid

1 个答案:

答案 0 :(得分:8)

原因很简单。您没有使用正确的文件格式。

您的.SaveAs代码应如下所示

.SaveAs "\myserver\test\xyz.xlsx", FileFormat:=51

请参阅下表中的文件格式

50 = xlExcel12 (Excel Binary Workbook in 2007-2010 with or without macro's, xlsb)
51 = xlOpenXMLWorkbook (without macro's in 2007-2010, xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2010, xlsm)
56 = xlExcel8 (97-2003 format in Excel 2007-2010, xls)

会推荐这个link