接收ActiveX自动化:错误索引错误消息

序幕

我正在开始一个新的项目,基本上我正在使用Excel作为另一个程序的日志。 这就是说,这是VBA(仅在使用Excel对象时)和VB6(主“主”编程语言)的混合。 这就是为什么这两种语言都被贴上标签,因为我预料到使用标签的可恶评论; 我正在寻找两种编程语言的混合解决scheme!
另外,我知道一些VBA活动人士会说永远不会使用ActiveSheet 。 我不关心这个,我想提前说谢谢 。 我在这个工作簿中有一张纸,因为它的主要function是作为日志。 ActiveSheet将始终是唯一的表单。


我有以下代码,我不太熟悉将工作簿设置为object ,这可能是我收到Bad Index错误的原因。

 Sub Test() ' Checking if Excel is open, if not, open it. Dim xL As Object, wBook As Object, iCloseThings As Byte On Error Resume Next Set xL = GetObject(, "Excel.Application") On Error GoTo 0 If xL Is Nothing Then iCloseThings = 1 ' Set Excel to close only if it was never open Set xL = CreateObject("Excel.Application") End If Set wBook = xL.Workbooks("C:\Users\<UserName>\Documents\<WorkBook>.xlsx").ActiveSheet If iCloseThings = 1 Then xL.Quit End sub 

我需要帮助的是如何正确设置这个对象来指向我在上面的例子中的确切工作簿? 我所知道的所有事情都是Set wBook = XL.Workbooks("<WorkBook>.xlsx").ActiveSheet是因为我知道这样的工作簿已经打开了。 但有可能不公开,我需要一些更灵活的东西。

感谢你的协助!

您需要处理一些不同的案例,主要取决于想要的工作簿是否已经打开,如果正在运行的Excel会话“被捕获”

你可能想要使用一些专用函数,而不是混淆你的主代码,并且在debugging和维护你的代码方面更加有效,如下所示

 Option Explicit Sub Test() ' Checking if Excel is open, if not, open it. Dim xL As Object, wBook As Object, wSheet As Object, iCloseThings As Byte Set xL = GetExcel(iCloseThings) Set wBook = GetExcelWorkbook(xL, "C:\Users\<UserName>\Documents\<WorkBook>.xlsx") If wBook Is Nothing Then Exit Sub Set wSheet = wBook.ActiveSheet If iCloseThings = 1 Then xL.Quit End Sub Function GetExcel(iCloseThings As Byte) As Object On Error Resume Next Set GetExcel = GetObject(, "Excel.Application") On Error GoTo 0 If GetExcel Is Nothing Then iCloseThings = 1 ' Set Excel to close only if it was never open Set GetExcel = CreateObject("Excel.Application") End If End Function Function GetExcelWorkbook(xL As Object, wbFullName As String) As Object Dim wbName As String wbName = Right(wbFullName, Len(wbFullName) - InStrRev(wbFullName, "\")) On Error Resume Next Set GetExcelWorkbook = xL.Workbooks(wbName) On Error GoTo 0 If GetExcelWorkbook Is Nothing Then Set GetExcelWorkbook = xL.Workbooks.Open(wbFullName) Else If GetExcelWorkbook.Path & "\" & wbName <> wbFullName Then MsgBox "A workbook with the wanted name '" & wbName & "' is already open but its path doesn't match the required one" _ & vbCrLf & vbCrLf & "Close the already open workbook and run this macro again", vbCritical + vbInformation Set GetExcelWorkbook = Nothing Else MsgBox "Wanted workbook is already open", vbInformation End If End If End Function