2011-07-06 39 views
1

我試圖在Access 2010中的表單對象中引用某些VBA代碼中的報表對象。我瞭解,在報表中,我可以使用語法Reports![report name]來引用報表名稱「report_name」,但這似乎並不適用於表單代碼。如何從表單中引用報表

所以我的問題是:如何從VBA代碼中爲表單對象引用報表對象?

+0

報告集合包括只開放報告,因此報告[報告名稱]將僅指所需的報告,如果它已經打開!您可以使用AllForms集合引用未打開的報告,但是您無法對打開的報告進行相同的處理。 –

回答

4

這裏是我的表單上的命令按鈕的單擊事件的代碼。它打開一個名爲rptFoo的報告,然後引用打開的表單來檢索其名稱屬性,並將名稱爲Debug.Print的名稱指定給立即窗口。

Private Sub cmdReferenceReport_Click() 
    DoCmd.OpenReport "rptFoo", acViewPreview 
    Debug.Print Reports!rptFoo.name '<- view this in Immediate window; Ctrl+g will take you there 
End Sub 

這裏是另一種方式來做到這一點。

Private Sub cmdReferenceReport_Click() 
    DoCmd.OpenReport "rptFoo", acViewPreview 
    Dim rpt As Report 
    Set rpt = Reports!rptFoo 
    Debug.Print rpt.name 
    Set rpt = Nothing 
End Sub 
+1

再次感謝你。您的帖子今天對我非常有幫助。 – rohrl77

1

@HansUp傳遞報告名稱作爲一個字符串變量(而不是一個字符串,你在你的代碼)時,我收到了運行時錯誤2451 - 「您輸入的報告名字‘所以reportName’拼寫錯誤或者指的是沒有開放或不存在的報告。「像OP,我還使用MS Access 2010中

我使用一個字符串變量報告名稱引用從表單報表解決方案是使用括號語法:報告(這裏字符串報告名稱變量)

例子:

Public Sub Set_Report_RecordSource(reportName As String, datasourceQueryName As String) 
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    ' Purpose: Sets a report's recordsource programmatically. Especially useful 
    ' for a report that is used by many forms. 
    ' Params: 
    ' reportName = Report whose RecordSource needs to be set. 
    ' datasourceQueryName = The query name that will return records to display 
    ' by the specified report (reportName). 
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    DoCmd.OpenReport reportName:=reportName, View:=acViewDesign 
    Reports(reportName).RecordSource = datasourceQueryName 
    DoCmd.Close ObjectType:=acReport, ObjectName:=reportName, Save:=acSaveYes 
End Sub 
相關問題