我有一段访问数据库的代码,并在我获取信息更改的数据库“表”中重复自身。
我的想法是用这段代码创建另一个子程序,每次我需要它时,我都会在“大”子程序中调用它。
变量
Task_Type
和 X_Loop
是会改变的
Dim strSQL As String
'Define SQL Query
strSQL = "SELECT * FROM X_Loop WHERE Sample = '" & Sample & "' AND Task_Type = '" & TaskType & "'"
'Create recordset with defined SQL Query
Set rst = New ADODB.Recordset
rst.Open strSQL, conn, adOpenForwardOnly
While rst.EOF <> True And rst.BOF <> True
SetTaskField Field:="Name", Value:=rst.Fields("Task_Name")
SetTaskField Field:="Task Type", Value:=rst.Fields("Task_Type")
SelectTaskField Row:=0, Column:="duration", Width:=2
SetTaskMode Manual:=True
EditClear Contents:=True
SelectRow Row:=1
InsertTask
rst.MoveNext
Wend
每当您遇到这样的问题,并且您知道要封装在子程序中的代码有许多要更改的变量时,这些变量就会成为新子程序的参数:
Option Explicit
Private Sub Command1_Click()
'call the sub wherever you need
AccessTheDatabase "X_Loop", "My Sample", "My Task"
End Sub
Private Sub AccessTheDatabase(ByVal TableName As String, ByVal Sample As String, ByVal TaskType As String)
Dim strSQL As String
Dim rst As ADODB.Recordset
strSQL = "SELECT * FROM " & TableName & " WHERE Sample = '" & Sample & "' AND Task_Type = '" & TaskType & "'"
Set rst = New ADODB.Recordset
rst.Open strSQL, conn, adOpenForwardOnly
While rst.EOF <> True And rst.BOF <> True
'do whatever you need
rst.MoveNext
Wend
End Sub
当然,您应该将子命名为在您的应用程序上下文中有意义的名称。