错误91 - 未设置对象

时间:2012-10-08 03:40:40

标签: excel-vba vba excel

这是发布与错误91有关的#12772920的延续。好的,这是情况。 (1)如果该行被注释掉,则(2)产生错误91.如果没有注释掉,代码运行正常。 (3)这应该将公共物品公司指向“公司”表,不应该吗?我很困惑为什么这一行似乎没有按照(1)的方式设置shCompanies对象。

Option Explicit
Public wbCode As Workbook

Public Sub Main()
   Dim tables As New CTables
   Set wbCode = ThisWorkbook
   Call SetExcelObjects
   (2)Call tables.Indexing
End Sub

Public Sub SetExcelObjects()
   Dim tables As New CTables
   (3)Set tables.shCompanies = wbCode.Worksheets("Companies")   
End Sub


---Class Module CTables
Option Explicit
Public shCompanies As Worksheet

Public Sub Indexing()
   Dim rng As Long
   Dim tables As New CTables
   (1)Set tables.shCompanies = wbCode.Worksheets("Companies")
   rng = tables.shCompanies.UsedRange.Rows.Count
End Sub

1 个答案:

答案 0 :(得分:0)

您需要将tables声明为CTables的公开实例。然后你可以从不同的模块中采取行动。重新声明它就像你一直在“擦拭板岩清洁”并导致你看到的错误。您当然不希望在CTables内声明表的实例。

请注意,最佳做法是将实例化表与其声明分开,因此Set tables = New CTables中的行Main

以下编译并为我运行。我认为它符合您的期望:

Public wbCode As Workbook
Public tables As New CTables

Public Sub Main()
Set tables = New CTables
Set wbCode = ThisWorkbook
Call SetExcelObjects
Call tables.Indexing 
End Sub

Public Sub SetExcelObjects()
Set tables.shCompanies = wbCode.Worksheets("Companies")
End Sub

    'Class CTables
Public shCompanies As Worksheet

Public Sub Indexing()
   Dim rng As Long
   rng = shCompanies.UsedRange.Rows.Count
End Sub