2015-11-20 98 views
0

我的一項任務是創建一個大輸出,從而讓我通過程序生成屏幕,格式化輸出,然後剪切/粘貼爲打印屏幕。我寫了以下內容:展望簡化我的VBA

Range("B6:M6").Select 
Range(Selection, Selection.End(xlDown)).Select 
ActiveSheet.PageSetup.PrintArea = "$B$6:$M$300" 
Set ActiveSheet.HPageBreaks(1).Location = Range("B16") 
Set ActiveSheet.HPageBreaks(2).Location = Range("B26") 
Set ActiveSheet.HPageBreaks(3).Location = Range("B36") 
Set ActiveSheet.HPageBreaks(4).Location = Range("B46") 
Set ActiveSheet.HPageBreaks(5).Location = Range("B56") 
Set ActiveSheet.HPageBreaks(6).Location = Range("B66") 

......等等每十行。然後我做了它,它會逐頁剪切和粘貼每個打印區域,並將其放在最後一頁上。這樣,我可以輕鬆地將每個轉換爲.ppt。最終,我想學習足夠的自動化整個過程,但要採取步驟。剪切/粘貼/打印看起來是這樣的:

Range("B6:M15").Select 
Selection.CopyPicture Appearance:=xlPrinter, Format:=xlPicture 
Sheets("Sheet2").Select 
ActiveSheet.Paste 
ActiveSheet.Shapes.Range(Array("Picture 1")).Select 
Selection.ShapeRange.Width = 719.28 

Sheets("Private Company (w Debt)").Select 
Range("B16:M25").Select 
Selection.CopyPicture Appearance:=xlPrinter, Format:=xlPicture 
Sheets("Sheet2").Select 
ActiveSheet.Paste 
ActiveSheet.Shapes.Range(Array("Picture 2")).Select 
Selection.ShapeRange.Width = 719.28 

Sheets("Private Company (w Debt)").Select 
Range("B26:M35").Select 
Selection.CopyPicture Appearance:=xlPrinter, Format:=xlPicture 
Sheets("Sheet2").Select 
ActiveSheet.Paste 
ActiveSheet.Shapes.Range(Array("Picture 3")).Select 
Selection.ShapeRange.Width = 719.28 

在我的宏,代碼直接跟隨分頁符(這就像40頁左右),它運行體面良好。

有沒有人可以告訴我怎樣才能更直觀地寫這個,這樣VBA就知道每十行設置一個水平分頁符,然後打印剪切/粘貼而不用物理寫出每行並指定確切的單元格?

+0

晚自習變量?編輯:看到[這](http://stackoverflow.com/questions/30378320/excel-vba-loop-through-range)。 – findwindow

+2

也許這對於[CodeReview](http://codereview.stackexchange.com/)而不是SO更好。此外,這將大大有助於學習[如何避免'.Select'](http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros)。使用宏記錄器在Excel中執行一些簡單,中等和「困難」的事情,並查看代碼以瞭解其工作原理。看起來你只需要花一些時間來學習VB,但只要學習如何刪除'.Select',它將*極大地*幫助啓動你的理解,因爲你將學習如何直接處理數據,而不是選擇 – BruceWayne

+1

查看循環。 '因爲我= 6到295第10步'會循環每十個地方我會重新發送行號。同時調整大小,這將允許您使用第一個單元格Range(「B」&i).resize(10,13)將您的區域設置爲圖像複製。 –

回答

0

嗯是這樣的:

Dim i as Long 
Dim copyRange as Range 
Range("B6:M6").Select 
Range(Selection, Selection.End(xlDown)).Select 
ActiveSheet.PageSetup.PrintArea = "$B$6:$M$300" 


For i = 1 to 6 '## Modify from 6 to a larger number, as needed 
    'Set up your page break locations 
    Set ActiveSheet.HPageBreaks(i).Location = Range("B" & 6 + (10 * i)) 
    'copy/paste in to Sheet2: 
    ' use the resize method to get a 10 rows x 12 columns range 
    Set copyRange = ActiveSheet.HPageBreaks(i).Location.Resize(10, 12) 
    'copyPicture: 
    copyRange.CopyPicture Appearance:=xlPrinter, Format:=xlPicture 

    With Workshheets("Sheet2") 
     .Paste 
     .Shapes.Range(Array("Picture " & i)).ShapeRange.Width = 719.28 
    End With 

Next