2012-11-25 164 views
2

我正在嘗試設置一個動態打印範圍,以在同一工作簿中的另一張工作表中填充工作簿中打印工作表。 我似乎有麻煩。我成立了名稱管理器中的命名範圍稱爲橫向如下:Excel 2010中的動態打印範圍

= OFFSET( '幻燈頁打印橫向' $ A $ 27 0,0,COUNTA( '幻燈頁打印橫向' $ A!: $ A),COUNTA( '幻燈頁打印橫向' $ 1:$ 1))

我堅持嘗試寫VBA代碼(我一無所知VBA)我有這個...

Sub Printarea() 
    ActiveSheet.PageSetup.Printarea = "lateral" 
End Sub 

我收到一個錯誤「運行時錯誤」1004'「

任何人都可以幫忙嗎?

+1

顯然我沒有使用你的電子表格,但我根據你的代碼在本地做了一個測試,它似乎沒有任何錯誤地工作。 – Neil

+0

確保'lateral'在工作簿級別而不是在工作表級別上定義,否則您可能必須使用'Slide Sheet Print Lateral!lateral'限定名稱。請參閱[此MSDN](https://office.microsoft.com/en-us/excel-help/define-and-use-names-in-formulas-HA010147120.aspx)以獲取更多詳細信息 – SeanC

回答

0

最後兩個參數指定範圍「lateral」的高度和寬度。他們計算非空單元的數量。像尼爾,我發現你的代碼沒有問題的前提是:

  • 您是在幻燈片頁打印橫向片(否則參考Activesheet將BARF因爲你想設置打印範圍活動工作表不同紙張上的範圍); AND
  • 「幻燈片打印橫向」頁面的A列和第1行中有一些內容。但是,如果沒有,則會爲零範圍指定高度和/或寬度。這是一個無效的範圍參考,然後你會得到1004錯誤。

您可以安全避免的唯一方法是在分配範圍之前獲取VBA代碼中的CountA值;如果其中任一個爲零,則警告用戶並中止。

我還建議您不要使用方法或屬性名稱來處理這樣的過程;你經常可以擺脫它,但有時它可能會導致問題。調用像SetMyPrintRange這樣的程序是安全的。

編輯:經過反思,我不會爲檢查計數而煩擾;只是試圖獲得對範圍的參考,如果你不能,然後告訴用戶該做什麼。試試這個:

Sub SetMyPrintArea() 

    Dim l As Long 
    Dim wks As Excel.Worksheet 
    Dim rng As Excel.Range 

    'Check that the worksheet exists. 
    On Error Resume Next 
    Set wks = ThisWorkbook.Worksheets("Slide Sheet Print Lateral") 
    On Error GoTo ErrorHandler 

    'If it doesn't, throw an error which will send it to the error handler. 
    If wks Is Nothing Then 
     Err.Raise vbObjectError + 20000, , _ 
     "The worksheet Slide Sheet Print Lateral is not in this workbook." 
    End If 

    'Try to get the reference to the range. If we can't, there's something wrong. 
    On Error Resume Next 
    Set rng = wks.Range("lateral") 
    On Error GoTo ErrorHandler 

    If rng Is Nothing Then 
     Err.Raise vbObjectError + 20000, , _ 
     "Cannot find the range named 'lateral'. Please ensure that there is " _ 
     & "content in row 1 and column A of the Slide Sheet Lateral sheet." 
    End If 

    wks.PageSetup.Printarea = "lateral" 

ExitPoint: 

'Just cleaning up the object references 
'to leave the place tidy... 
On Error Resume Next 
Set rng = Nothing 
Set wks = Nothing 
On Error GoTo 0 

Exit Sub 

ErrorHandler: 

'Display the message and go to the exit point. 
MsgBox "Error " & Err.Number & vbCrLf & Err.Description 

Resume ExitPoint 

End Sub