【发布时间】:2021-06-15 00:33:04
【问题描述】:
我有一个宏,它在 CSV 上运行与个人工作簿不同的循环宏(无需打开它),并且应该使用相同的名称重新保存文档。
我在尝试保存时收到此错误。
运行时错误“1004”:
您不能使用与另一个打开的工作簿或加载项相同的名称保存此工作簿。在保存之前选择其他名称或关闭其他工作簿或加载项。
我需要这个,因为有一个工具可以查找此文档名称。
这是打开 csv 并运行循环宏(不打开 Excel)的宏。
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("F:\Folder\specific name.csv", 0, True)
xlapp.workbooks.open("C:\Users\name\AppData\Roaming\Microsoft\Excel\XLSTART \Personal.xlsb")
xlApp.Run "Personal.xlsb!LoopColumnC "
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
LoopColumnC 的宏是它尝试保存的位置。
Sub LoopColumnC()
'
' LoopColumnC Macro
'
'
'This is to disregard any popups.
Application.DisplayAlerts = False
'This is the actual loop. Works just fine.
Dim lastRow As Long
lastRow = Cells(Rows.Count, 3).End(xlUp).Row
For i = 2 To lastRow
If Cells(i, 3).Value = 1 Then Cells(i, 3).Value = Cells(i - 1, 3).Value
Next i
'Here is where it errors out because the file it is trying to save as is already opened in the background.
ThisWorkbook.SaveAs "F:\Folder\specific name.csv",
Application.DisplayAlerts = True
End Sub
【问题讨论】:
-
您正在尝试将您的个人工作簿另存为 csv 文件,该文件已在
Excel的另一个实例中打开。当您使用个人工作簿中的代码时,您很少使用ThisWorkbook。 -
那么,让它保存它更新的 csv 的函数是什么?哪里是放置该代码的最佳位置?在 ExcelMacroExample 宏中还是在 LoopColumnC 中?
-
"没有实际打开它" ...但是你正在用
Workbooks.Open("F:\Folder\specific name.csv", 0, True)打开它。那么,为什么不直接使用ActiveWorkbook.Save而不是ThisWorkbook.SaveAs ...