获取Excel工作表的实际打印区域(通过VBA)

时间:2014-04-05 10:43:14

标签: vba excel-vba excel

如何在Excel中获得实际使用范围(包括图表)?

问题是,用户不会定义任何打印区域。但他应该在剪贴板中获得所有使用范围(包括图表)的图片:

如果我喜欢,Sheet1.PageLayout.PrintArea它给了我一个空白字符串。

如果我喜欢,Sheet1.UsedRange.Address, 它没有考虑底部的图表。

请建议解决方法。

感谢。

1 个答案:

答案 0 :(得分:1)

您无法使用 ChartObject TopLeftCell BottomRightCell ,并检查某些图表是否在UsedRange之外?像这样:

Sub test()
    Dim usedRangeEx As Range
    Set usedRangeEx = GetUsedRangeIncludingCharts(Worksheets("Sheet1"))
    usedRangeEx.Activate
    Debug.Print usedRangeEx.Address
End Sub

Private Function GetUsedRangeIncludingCharts(target As Worksheet) As Range
    Dim firstRow As Long
    Dim firstColumn As Integer
    Dim lastRow As Long
    Dim lastColumn As Integer
    Dim oneChart As ChartObject

    With target
        firstRow = .UsedRange.Cells(1).Row
        firstColumn = .UsedRange.Cells(1).Column
        lastRow = .UsedRange.Cells(.UsedRange.Cells.Count).Row
        lastColumn = .UsedRange(.UsedRange.Cells.Count).Column

        For Each oneChart In .ChartObjects
            If oneChart.TopLeftCell.Row < firstRow Then _
                firstRow = oneChart.TopLeftCell.Row
            If oneChart.TopLeftCell.Column < firstColumn Then _
                firstColumn = oneChart.TopLeftCell.Column
            If oneChart.BottomRightCell.Row > lastRow Then _
                lastRow = oneChart.BottomRightCell.Row
            If oneChart.BottomRightCell.Column > lastColumn Then _
                lastColumn = oneChart.BottomRightCell.Column
        Next oneChart

        Set GetUsedRangeIncludingCharts = .Range(.Cells(firstRow, firstColumn), _
                                                 .Cells(lastRow, lastColumn))
    End With

End Function