【发布时间】:2015-04-06 15:23:43
【问题描述】:
关于在 VBA 中使用简单类的机制有几个非常好的答案:When to use a Class in VBA? 和 What are the benefits of using Classes in VBA?
作为一个对 OOP 和类的相对新手,很难知道如何实现它们,或者什么是真正可能的。
例如,我必须处理多张工作表中的大范围,并且需要获取许多不同的数据子集。 “做 x 的代理人”和“有 y 的客户”……等等。这是我汇总的一个子项,用于计算拥有超过 2 个客户的代理的数量:
Sub agent_subset(output_sheet As String, _
Input_sheet_name As String, _
email_col As Integer, _
vendor_count_col As Integer, _
client_count_col As Integer, _
modified_col As Integer, _
num_of_clients As Integer)
' get a list of all agents with 2 or more clients and put them into a sheet
Application.DisplayStatusBar = True
Dim sheet_rows As Long
sheet_rows = Worksheets(Input_sheet_name).Cells(rows.Count, 1).End(xlUp).Row
Dim email_range As Range ' range of agent emails
Dim client_count_range As Range ' range of client count
Dim vendor_count_range As Range ' range of vendor count
Dim modified_range As Range ' range of modified at
With Worksheets(Input_sheet_name)
Set email_range = .Range(.Cells(2, email_col), .Cells(sheet_rows, email_col))
Set client_count_range = .Range(.Cells(2, client_count_col), .Cells(sheet_rows, client_count_col))
Set vendor_count_range = .Range(.Cells(2, vendor_count_col), .Cells(sheet_rows, vendor_count_col))
Set modified_range = .Range(.Cells(2, modified_col), .Cells(sheet_rows, modified_col))
End With
Dim n As Long
Dim counter As Long
counter = 0
Dim modified_array() As String
For n = 2 To sheet_rows
If client_count_range(n, 1).Value > num_of_clients Then
counter = counter + 1
Worksheets(output_sheet).Cells(counter + 1, 1).Value = email_range(n, 1).Value
Worksheets(output_sheet).Cells(counter + 1, 2).Value = client_count_range(n, 1).Value
Worksheets(output_sheet).Cells(counter + 1, 3).Value = vendor_count_range(n, 1).Value
modified_array() = Split(modified_range(n, 1).Value, "T")
Worksheets(output_sheet).Cells(counter + 1, 4).Value = modified_array(0)
End If
Application.StatusBar = "Loop status: " & n & "of " & sheet_rows
Next n
Worksheets(output_sheet).Cells(counter + 3, 1).Value = "Last run was " & Now()
Application.StatusBar = False
End Sub
效果很好,但现在我想根据其他标准获得更小的代理和客户子集。所以,我要写一个类似的函数,处理类似的数据。我的直觉告诉我,使用类会让我的生活更轻松,但我不知道如何分解任务。
是否应该有一个包含所有代理信息的代理类?和/或客户端类?或者,这些类是否应该用于查看整个范围或工作表?
我不是在寻找特定的代码,而是一种关于如何分解事物的方法。
【问题讨论】: