将工作表另存为对象属性

问题描述 投票:0回答:1

我有一个具有属性

Employee
Name
Worksheet
类,用于编译员工加班表。以下代码循环访问一个文件夹,创建一个 Employee 并将其添加到字典中。我的问题是,一旦我们脱离了循环,工作表就变成了一个通用对象,所以我无法对其进行任何操作!

Sub ImportEmployeeFilesTest()
    Dim FolderPath As String
    Dim FileName As String
    Dim wb As Workbook
    Dim employee As EmployeeObject
    Dim EmployeesDict As Object
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    FolderPath = "C:\Users\000379070\Desktop\VSCode\data\"
    FileName = Dir(FolderPath & "*_PunchClock.xlsm")
    
    Set EmployeesDict = CreateObject("Scripting.Dictionary")

    Do While FileName <> ""
        Set wb = Workbooks.Open(FolderPath & FileName)
        
        Set employee = New EmployeeObject

        employee.SetWorksheet wb.Sheets(1)
        EmployeesDict.Add employee.Name, employee
        
        MsgBox TypeName(EmployeesDict(employee.Name).EmployeeWorksheet) ' This prints Worksheet
    
        wb.Close False
        FileName = Dir
    Loop
    MsgBox TypeName(EmployeesDict("Peter-Nicholas").EmployeeWorksheet) ' This prints Object
        
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

EmployeeObject.cls

Option Explicit

Public Name As String
Public EmployeeWorksheet As Worksheet

Private Sub Class_Initialize()

End Sub

Public Sub SetWorksheet(ws As Worksheet)
    Set EmployeeWorksheet = ws
    Me.SetName
End Sub

Public Sub SetName()
    If Not EmployeeWorksheet Is Nothing Then
        Me.Name = EmployeeWorksheet.Range("A2").Value
    Else
        Err.Raise vbObjectError + 1000, "Employee.SetName", "Worksheet is not set!"
    End If
End Sub

我不知道为什么会发生这种情况,并且在论坛上找不到有同样问题的人!我尝试使用集合而不是字典,但我得到了完全相同的结果......请帮助!

excel vba dictionary worksheet
1个回答
0
投票

这是由于关闭

wb
,而不是由于使用
Dictionary
Collection
。如果没有父级
Worksheet
Workbook
就不可能存在。

一个简单的例子:

Sub Test()
    Dim wb As Workbook
    Set wb = Workbooks.Add
    
    Dim ws As Worksheet
    Set ws = wb.Worksheets(1)
    Debug.Print TypeName(ws) ' Worksheet
    
    wb.Close False
    Debug.Print TypeName(ws) ' Object
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.