不确定我为什么会收到此错误。请协助纠正,并提供一个很好的解释原因。我有3个子(从2个模块)顺序相互调用。是错误消息的原因,因为第一个子文件中的文件名被声明为第三个子中的变量?请参阅以下代码:
模块1:
Option Explicit
Sub PRM_1_Report_Save()
'
Application.ScreenUpdating = False
Dim PRM_1_New As Workbook ' This is BCRS-PTASKS Unassigned.csv
Set PRM_1_New = Workbooks("BCRS-PTASKS Unassigned.csv")
Dim SaveDir1 As String, prmAfn As String
SaveDir1 = CreateObject("WScript.Shell").SpecialFolders("MyDocuments") & "\PRM Temp Files"
If Len(Dir(SaveDir1, vbDirectory)) = 0 Then MkDir SaveDir1
prmAfn = SaveDir1 & "\PRM_1_TEMP"
Application.SendKeys ("~")
PRM_1_New.SaveAs Filename:=prmAfn, FileFormat:=xlOpenXMLWorkbook
PRM_1_New.Close False
Call PRM_2_Report_Save
Application.ScreenUpdating = True
End Sub
Sub PRM_2_Report_Save()
'
Application.ScreenUpdating = False
Dim PRM_2_New As Workbook ' This is Problem WGM & WGL xref with description.xls
Set PRM_2_New = Workbooks("Problem WGM & WGL xref with description.xls")
Dim SaveDir2 As String, prmBfn As String
SaveDir2 = CreateObject("WScript.Shell").SpecialFolders("MyDocuments") & "\PRM Temp Files"
If Len(Dir(SaveDir2, vbDirectory)) = 0 Then MkDir SaveDir2
prmBfn = SaveDir2 & "\PRM_2_TEMP"
Application.SendKeys ("~")
PRM_2_New.SaveAs Filename:=prmBfn, FileFormat:=xlOpenXMLWorkbook
PRM_2_New.Close False
Application.ScreenUpdating = True
Call Open_PRM_Files
End Sub
第2单元:
Option Explicit
Sub Open_PRM_Files()
'
Application.ScreenUpdating = False
Dim PRM_Dir As String
Dim PRM_1_TEMP As Workbook
Set PRM_1_TEMP = Workbooks("PRM_1_TEMP.xlsx") ' This is the line that get's the error
Dim PRM_2_TEMP As Workbook
Set PRM_2_TEMP = Workbooks("PRM_2_TEMP.xlsx")
PRM_Dir = CreateObject("WScript.Shell").SpecialFolders("MyDocuments") & "\PRM Temp Files"
Workbooks.Open Filename:=PRM_Dir & "\" & PRM_1_TEMP
Workbooks.Open Filename:=PRM_Dir & "\" & PRM_2_TEMP
Application.ScreenUpdating = True
End Sub
Module2中sub的这一行是调试器显示错误的地方(在上面的子语句中也有注释):
Set PRM_1_TEMP = Workbooks("PRM_1_TEMP.xlsx")
此处代码的目的是将两个导入的报告保存为.xlsx格式,关闭它们,然后以保存的格式打开文件。我需要在单独的子(保存和打开)中发生此VBA项目的其他工作流程(此处未列出(或相关))。
编辑:我还应该提到前两个子程序执行并提供预期的结果,即每个文件保存在新目录中并具有适当的扩展名。
答案 0 :(得分:1)
Set PRM_1_TEMP = Workbooks("PRM_1_TEMP.xlsx")
此行假定您已经拥有一个具有该名称的打开工作簿。如果Excel找不到具有该名称的打开的工作簿,那么您将发现运行时错误。
我假设您正在尝试打开您在前两个潜艇中创建的工作簿:
Workbooks.Open Filename:=PRM_Dir & "\" & PRM_1_TEMP
Workbooks.Open Filename:=PRM_Dir & "\" & PRM_2_TEMP
"&安培; PRM_1_TEMP"是Workbook变量的名称,您尝试将其连接为字符串名称。将此更改为与文件名匹配的字符串,然后将工作簿的声明移动到打开工作簿的代码下方。这样,Excel在尝试在Workbooks集合中访问它们之前打开工作簿,并且您不应该收到错误。我还没有测试过这个修改,但请告诉我它是否适合您。
Sub Open_PRM_Files()
Application.ScreenUpdating = False
Dim PRM_Dir As String
PRM_Dir = CreateObject("WScript.Shell").SpecialFolders("MyDocuments") & "\PRM Temp Files"
Workbooks.Open Filename:=PRM_Dir & "\" & "PRM_1_TEMP"
Workbooks.Open Filename:=PRM_Dir & "\" & "PRM_2_TEMP"
Dim PRM_1_TEMP As Workbook
Set PRM_1_TEMP = Workbooks("PRM_1_TEMP.xlsx") ' This is the line that get's the error
Dim PRM_2_TEMP As Workbook
Set PRM_2_TEMP = Workbooks("PRM_2_TEMP.xlsx")
Application.ScreenUpdating = True
End Sub