访问VBA:使用现有的Excel工作簿(运行时错误9,如果文件已经打开)
我在Access中写一个macros(希望)会:
-
创build一个Excel工作表
-
根据Access数据库中的信息进行设置和格式化
-
用户input后,将input的数据馈送到现有的Excel主文件中
打开空白纸等工作绝对好,但我卡住试图将现有的主文件设置为一个variables :
Sub XLData_EnterSurvey() Dim appXL As Excel.Application Dim wbXLnew, wbXLcore As Excel.Workbook Dim wsXL As Excel.Worksheet Dim wbXLname As String Set appXL = CreateObject("Excel.Application") appXL.Visible = True wbXLname = "G:\[*full reference to file*].xlsm" IsWBOpen = fnIsWBOpen(wbXLname) 'separate function (Boolean), using 'attempt to open file and lock it' method 'from Microsoft site. If IsWBOpen = False Then Set wbXLcore = appXL.Workbooks.Open(wbXLname, True, False) 'open file and set as variable. ElseIf IsWBOpen = True Then wbXLcore = appXL.Workbooks("ResultsOverall.xlsm") 'ERROR HERE. 'file is already open, so just set as variable. End If Debug.Print wbXLcore.Name Debug.Print IsWBOpen Set appXL = Nothing End Sub
当文件closures时,这个效果很好。 但是,当它打开时,我得到:
运行时错误“9”:下标超出范围
我只是开始教自己的VBA(非常反复无常!),而且我在这里看到的答案都没有,Google似乎很适合这个问题,所以我有点失落…
考虑到它在文件closures时工作正常 ,我怀疑我只是在引用该文件时犯了一些愚蠢的错误 – 可能与“createobject”位和不同的excel实例有关?
我们欢迎所有的build议! 谢谢
谢谢@StevenWalker
这是工作代码:
Sub XLData_EnterSurvey() Dim appXL As Excel.Application Dim wbXLnew As Excel.Workbook, wbXLcore As Excel.Workbook Dim wsXL As Excel.Worksheet On Error GoTo Handler Set appXL = GetObject(, "Excel.Application") appXL.Visible = True Dim wbXLname As String wbXLname = "G:\ [...] .xlsm" IsWBOpen = fnIsWBOpen(wbXLname) If IsWBOpen = False Then Set wbXLcore = appXL.Workbooks.Open(wbXLname, True, False) ElseIf IsWBOpen = True Then Set wbXLcore = appXL.Workbooks("ResultsOverall.xlsm") End If Set appXL = Nothing '-------------------Error handling------------------ Exit Sub ' For if excel is not yet open. Handler: Set appXL = CreateObject("Excel.Application") Err.Clear Resume Next End Sub
对不起,我在我的手机上,所以我不能进入太多的细节或代码很多,但一眼看去,我认为你可能需要添加一个error handling程序,如果文件已经打开,不同的线的代码被执行。
添加“错误去处理程序”(在创buildExcel对象之前),并在您的代码底部添加“处理程序:”。 在error handling程序中,使用get对象而不是创build对象。
您必须确保在error handling程序之前使用exit sub,否则每次运行代码时都会运行处理程序。
你可以在这里看到一个例子: 如何在Outlook邮件正文中插入图表或graphics
虽然请注意,在这个例子中,这是相反的(如果错误'获取'outlook,然后创build它)。
链接示例:
设置myOutlook = GetObject(,“Outlook.Application”)Set myMessage = myOutlook.CreateItem(olMailItem)
其余的代码在这里
退出小组
如果Outlook未打开,请打开它
处理器:
设置myOutlook = CreateObject(“Outlook.Application”)Err.Clear继续下一步
End sub
如果将appXL.Workbooks
语句移动到debugging窗口,则会发现该集合中的项目名称没有扩展名。
所以在你的情况下,我猜这行应该是这样的:
wbXLcore = appXL.Workbooks("ResultsOverall")