簡體   English   中英

將Excel打印區域復制到Word

[英]Copy Excel print area to Word

我想將Excel中的橫向打印區域復制到我的Word文檔中,從中運行代碼。

我在用

wb.Sheets("Sheet1").Range("A1:N33").Copy

復制區域,但是隨着列寬的變化,它是無用的。

更新:

我正在用它來計算我的Word文檔中的可用尺寸

With ActiveDocument.PageSetup
      UsableWidth = .PageWidth - .LeftMargin - .RightMargin
      UsableHeight = .PageHeight - .TopMargin - .BottomMargin
End With

我嘗試縮放圖像以適合:

Selection.PasteSpecial Link:=False, DataType:=wdPasteMetafilePicture, Placement:=wdInLine, DisplayAsIcon:=False
Selection.ShapeRange.Height = UsableHeight
Selection.ShapeRange.Width = UsableHeight

它並沒有完全做到這一點。 最好的方法是復制之前設置圖像范圍。

更新2:

Dim objExcel As New Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Set wb = objExcel.Workbooks.Open("C:\test.xlsx")
Set ws = wb.Sheets("Sheet1")

這給出了一個錯誤:

Set rngTemp = ws.Range("A1")

您可以使用以下代碼檢索打印區域信息:

Sub GetPrintArea()

Dim rngPrintArea As Range

'Put print area into range variable
Set rngPrintArea = Sheet1.Range(Sheet1.PageSetup.PrintArea)

'Perform operations on range - shows up in Immediate window:
Debug.Print rngPrintArea.Height
Debug.Print rngPrintArea.Width
Debug.Print rngPrintArea.Cells(rngPrintArea.Rows.Count, rngPrintArea.Columns.Count).Address

End Sub

如果尚未設置打印區域,則此方法不起作用-您可以確認是否已將Excel圖紙設置為橫向並定義了打印區域? 如果不是,則需要找到紙張尺寸並遍歷單元格,直到找到共享相同“左”和“上”值的單元(我認為)。 您可以這樣設置PrintArea:

'Set print area
Sheet1.PageSetup.PrintArea = "$A1:$N33"

編輯-這應該做您需要做的,因為我們知道源尺寸是預定義的-您需要在Word中設置UseableWidth和UseableHeight,然后使用ByVal或公共變量將它們帶入此子級:

Sub FindRange()

Dim rngTemp As Range, rngCopy As Range, rngTest As Range
Dim iCol As Integer, iRow As Integer

Set rngTemp = Sheet1.Range("A1")

'Get closest column
Do Until rngTemp.Left >= UseableWidth
        Set rngTemp = rngTemp.Offset(0, 1)
Loop
iCol = rngTemp.Column

'Get closest row
Do Until rngTemp.Top >= UseableHeight
        Set rngTemp = rngTemp.Offset(1, 0)
Loop
iRow = rngTemp.Row

Set rngCopy = Sheet1.Range("A1", Sheet1.Cells(iRow, iCol))

'Copy rngCopy into Word as you were before

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM