我在Excel中使用VB(Office 2010)。
我有一个名为Problem的类和一个生成随机问题的vb代码,每个问题都会创建一个新的工作表并将问题的参数打印到该工作表。
当我处理该工作表时,我需要一些存储在生成工作表的Problem对象实例中的参数并动态更改它们。
我想要做的是将问题的一个实例与其工作表相关联 类似的东西:
Dim p as Problem
Set p = new Problem
Worksheet("Problem 1").**myCurrentProblem** = p
然后可以访问变量myCurrentProblem
有办法吗?
提前感谢。
答案 0 :(得分:1)
或者如果有一个类问题表哪个绑定工作表和问题实例呢?这些实例将存储在 ProblemSheets 的集合中。示例(有点太长的例子,但HTH)。
ThisWorkbook类代码:
Private m_problemSheets As Collection
Public Sub AddProblemSheet(problemSheetParameter As ProblemSheet)
If m_problemSheets Is Nothing Then _
Set m_problemSheets = New Collection
m_problemSheets.Add problemSheetParameter, problemSheetParameter.SheetInstance.Name
End Sub
Public Function ProblemOfSheet(sheetName As String) As ProblemSheet
On Error Resume Next
Set ProblemOfSheet = m_problemSheets(sheetName)
On Error GoTo 0
End Function
Private Sub Workbook_Open()
Set m_problemSheets = New Collection
End Sub
问题类模块:(仅用于测试目的)
Public Name As String
问题表类模块:
Private m_problem As Problem
Private m_sheet As Worksheet
Public Sub Bind(problemParametr As Problem, sheetParameter As Worksheet)
Set m_problem = problemParametr
Set m_sheet = sheetParameter
End Sub
Public Property Get ProblemInstance() As Problem
Set ProblemInstance = m_problem
End Property
Public Property Set ProblemInstance(newProblem As Problem)
Set m_problem = newProblem
End Property
Public Property Get SheetInstance() As Worksheet
Set SheetInstance = m_sheet
End Property
标准模块代码:
Sub test()
Dim i As Integer
Dim newProblem As Problem
Dim newProblemSheet As ProblemSheet
' add data to collection first
For i = 1 To Worksheets.Count
Set newProblem = New Problem
newProblem.Name = "Problem_" & i
Set newProblemSheet = New ProblemSheet
newProblemSheet.Bind newProblem, Worksheets(i)
ThisWorkbook.AddProblemSheet newProblemSheet
Next
' get problem from collection by sheet name
Dim ps As ProblemSheet
Set ps = ThisWorkbook.ProblemOfSheet(Worksheets("Problem 1").Name)
If Not ps Is Nothing Then _
Debug.Print ps.ProblemInstance.Name
' set problem instance to another problem :-)
Dim myCurrentProblem As Problem
Set myCurrentProblem = New Problem
myCurrentProblem.Name = "myCurrentProblem 1"
Set ThisWorkbook.ProblemOfSheet(Worksheets("Problem 1").Name).ProblemInstance = myCurrentProblem
Debug.Print ThisWorkbook.ProblemOfSheet(Worksheets("Problem 1").Name).ProblemInstance.Name
End Sub