使用指定的变量循环进入类模块

时间:2018-01-18 17:04:48

标签: vba excel-vba class variables excel

我试图遍历员工列表并将其添加到类模块中。我的包版是弄清楚如何使用for循环中使用的声明变量作为类的实例。

基本上,我想将nameValue用作employeeNew EmployeeClass

这个想法是在当前迭代中使用员工的字符串值来填充类,而不是必须手动调暗/设置。

会感激任何帮助!

Option Explicit
Sub Vacation()
   Dim i As Integer
   Dim rowNum As Integer: rowNum = 5
   Dim colNum As Integer: colNum = 4
   Dim Vac As Integer: Vac = 46
   Dim obj, obj1 As Range
   Dim onePersonLoop As Range
   Dim nameLocation As Range
   Dim vacLocation As Range
   Dim emp_vacDates As Range

   For i = 2 To 2
      With ActiveWorkbook.Worksheets(i)

           Set onePersonLoop = .Cells(rowNum,_ 
                   colNum).Offset(-1).End(xlToRight).Offset(, -2)


           For rowNum = 5 To 359 Step 6

               Dim emps As Collection
               Set emps = New Collection
               Set nameLocation = .Cells(rowNum, colNum).Offset(-1,_                                                 
                -1).EntireRow.Cells(1, 2)
               Dim nameValue As String
               nameValue = nameLocation.Value

              Dim employee As EmployeeClass
              Set employee = New EmployeeClass                        
              emps.Add employee

           Next rowNum

       End With
   Next i
End Sub

课程模块:

 Option Explicit

 Dim vName As String
 Dim newCollection As Collection

 Public Property Get Name() As String
   Name = vName
 End Property

 Public Property Let Name(nme As String)
   vName = nme
   newCollection.Add nme

 End Property


 Private Sub Class_Initialize()
   Set newCollection = New Collection
   vName = ""
 End Sub

 Private Sub Class_Terminate()
   Set newCollection = Nothing
 End Sub

1 个答案:

答案 0 :(得分:0)

这是您的代码的简化版本,我认为这是您的核心问题。

我没有关注您的工作表布局:这只是从A1获取10个员工姓名:A10 -

Sub Tester()

    Dim emps As New Collection
    Dim emp As employee
    Dim c As Range

    For Each c In ActiveSheet.Range("A1:A10")
        Set emp = New employee
        emp.Name = c.Value
        emps.Add emp
    Next c

    For Each emp In emps
        Debug.Print emp.Name
    Next emp

End Sub

员工类:

Option Explicit

Dim vName As String

Public Property Get Name() As String
  Name = vName
End Property

Public Property Let Name(nme As String)
  vName = nme
End Property