【问题标题】:VBA Script fails when trying to save as .XLSX尝试另存为 .XLSX 时 VBA 脚本失败
【发布时间】:2016-10-21 09:24:41
【问题描述】:

已编写以下脚本以打开文件夹中的所有 .xlsm 文件类型并将它们保存为新目录中的 .xlsx 类型,但尝试另存为 .xlsx 时脚本一直失败。

返回的错误信息是运行时错误'1004'

所有解决此问题的尝试都失败了,非常感谢您的帮助,我提前感谢您。

Set fso = CreateObject("scripting.filesystemobject")
Set fils = fso.GetFolder("FILE LOCATION").Files

FldrPicker = "FILE LOCATION"
With FldrPicker
myPath = FldrPicker
End With
myExtension = "*.xlsm"
myfile = Dir(myPath & myExtension)

filepath = "NEW FILE LOCATION"

Do While myfile <> ""
Set wb = workbooks.Open(Filename:=myPath & myfile)
Application.DisplayAlerts = False
wb.SaveAs = myfile & ".xlsx"
wb.Close Savechanges:=True
Application.DisplayAlerts = True
Loop

【问题讨论】:

  • wb.SaveAs 不能被赋值,你需要给它一个参数 - 即wb.SaveAs myfile &amp; ".xlsx" (注意:如果你从“C”打开了一个名为“abc.xlsm”的文件:\Temp1\Temp2" 目录,您将在活动目录中创建一个名为“abc.xlsm.xlsx”的文件,这可能是 Excel 应用程序的存储位置 - 所以您可能真的想要 'wb.SaveAs myPath & Left( myfile, Len(myfile) - 5) & ".xlsx"`)
  • 我添加了以下参数,但返回相同的错误。 teamname = Left(myfile, Len(myfile) - 5) &amp; ".xlsx"Destination = filepath &amp; teamnamewb.SaveAs = Destination
  • 如果由于Excel 真的 不喜欢您尝试将macro enabled 工作簿保存为纯文件的警告而触发错误,请添加Application.DisplayAlerts = False 到代码的开头,Application.DisplayAlerts = True 作为强制问题的结尾。
  • 请阅读@YowE3K 答案。您仍在为 wb.SaveAs 赋值

标签: vba excel fso


【解决方案1】:

因为SaveAsWorkbook对象的Method,所以不能赋值,所以不能有如下形式的语句:

    wb.SaveAs = .....

MSDN documentation for SaveAs 表明它可以通过位置或名称传递许多参数:

表达式 .SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)

表达式表示工作簿对象的变量。

您所写内容的有效语法之一是:

    wb.SaveAs myfile & ".xlsx"

但是,如果您从“C:\Temp1\Temp2”目录中打开了一个名为“abc.xlsm”的文件,您将在当前目录中创建一个名为“abc.xlsm.xlsx”的文件,即可能存储 Excel 应用程序的位置 - 所以你可能真的想要

    wb.SaveAs FileName:=myPath & Left(myfile, Len(myfile) - 5) & ".xlsx"

或者可能

    wb.SaveAs FileName:=myPath & Left(myfile, Len(myfile) - 5) & ".xlsx", _
              FileFormat:=xlOpenXMLWorkbook

强制保存为非启用宏的格式。


但要记住的要点是……你不能给Method赋值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 2015-03-13
    • 2023-03-08
    • 2019-10-13
    • 1970-01-01
    相关资源
    最近更新 更多