我正在尝试将标题和一组数据复制到新工作表中进行打印。
虽然我可以很好地复制数据,但是列宽会丢失并且在其上运行自动调整会再次破坏页面。当页面最初设计时,手动设置列宽。
目前我有:
Dim tmp As Worksheet
Set tmp = Sheets.Add(after:=ActiveSheet)
RD.Copy tmp.Range("A1") ' Range data (set elsewhere)
RH.Copy tmp.Range("A1") ' Range header (set elsewhere)
我尝试过使用xlPasteSpecial和xlPasteAll,但在使用剪贴板时没有任何区别。
如何跨纸张复制单元格宽度需要做什么?
答案 0 :(得分:3)
您可以循环遍历源列,并设置目标范围的相应ColumnWidth:
Dim i As Integer
For i = 1 To sourceRange.Columns.Count
targetRange.Columns(i).ColumnWidth = sourceRange.Columns(i).ColumnWidth
Next
答案 1 :(得分:3)
格雷厄姆,
复制范围后,只需获取目标范围的列号,然后遍历源范围中的列,复制.ColumnWidth属性...
Dim RD As Range
Dim RH As Range
Set RH = Cells.Range("A1:C1")
Set RD = Cells.Range("A2:C2")
Dim tmp As Worksheet
Set tmp = Sheets.Add(after:=ActiveSheet)
RD.Copy tmp.Range("A1") ' Range data (set elsewhere)'
RH.Copy tmp.Range("A2") ' Range header (set elsewhere)'
' Get the column number of the first cell in the destination range'
' because it looks like we are just setting the first cell of the destination range'
' and letting Excel roll the range over'
Dim tmpCol As Integer
tmpCol = tmp.Range("A1").Cells(1, 1).Column ' make sure you use the same range value'
Now loop through the source columns setting the dest column to the same width.
For Each objCol In RH.Columns
tmp.Columns(tmpCol).ColumnWidth = objCol.ColumnWidth
tmpCol = tmpCol + 1
Next