VBA:Chart.export生成损坏的图像 - 直到滚动或chart.activate

时间:2017-11-10 13:45:14

标签: excel-vba charts vba excel

我有一个操作图表然后将其导出的表单,如下所示:

Workbooks(sWB).Sheets("Output").Unprotect sPW
Workbooks(sWB).Sheets("Output").ChartObjects(1).Chart.Export strDocName

然而,偶尔这不再适用,每次都会导出损坏的图像。转到带有图表的工作表并滚动它(不点击)解决了一段时间的问题。现在我把它修好了:

Workbooks(sWB).Sheets("Output").Unprotect sPW
Workbooks(sWB).Sheets("Output").ChartObjects(1).Activate    'chart sometimes falls asleep somehow, maybe this will fix
Workbooks(sWB).Sheets("Output").ChartObjects(1).Chart.Export strDocName

这似乎解决了我现在称之为“睡眠图表”的问题。

但是,我想了解它是如何工作的,并且在不使用“激活”的情况下修复它,因为这会影响我的用户(在此VBA-excel表单中使用多个Excel工作表)的用户体验。

任何了解这里发生了什么的人?

全功能代码链

Private Sub C171CmdLe1Dr1Graph_Click()
    Call ShowGraph(1, 1, True)
End Sub

Private Sub ShowGraph(ByVal intLeNr As Integer, ByVal intDrNr As Integer, ByVal Show As Boolean) 'Delete
    Dim strDocName As String
    Dim strLeNr As String
    Dim oChart As Frm_DCT_ShowGraph

    Call dle(intLeNr - 1).DrawChart(intLeNr, intDrNr)

    'export the chart
    strDocName = strMyDocsPath & "\DRT_Chart" & Right(strLeNr, 1) & ".gif"
    Workbooks(sWB).Sheets("Output").Unprotect sPW
    Workbooks(sWB).Sheets("Output").ChartObjects(1).Activate    'chart sometimes falls asleep somehow, maybe this will fix
    Workbooks(sWB).Sheets("Output").ChartObjects(1).Chart.Export strDocName
    If Show Then
        'create new chart, load it and show it
        Set oChart = New Frm_DCT_ShowGraph
        oChart.DocName = strDocName
        oChart.Show vbModeless
    End If
    Workbooks(sWB).Sheets("Output").Protect sPW

    DoEvents
End Sub

Public Sub DrawChart(ByVal intLeNr As Integer, ByVal intDrNr As Integer)
    Dim lngN As Long
    Dim sngPlotArr() As Single
    Dim strIRange As String
    Dim strURange As String

    ...

    'create plot data
    Call cDriver(intDrNr - 1).Plot(sngPlotArr)

    'unlock worksheet
    Workbooks(sWB).Sheets("Output").Unprotect sPW

    'clear range first
    Workbooks(sWB).Sheets("Output").Range(strIRange).Clear
    Workbooks(sWB).Sheets("Output").Range(strURange).Clear
    'fill in data
    For lngN = 0 To UBound(sngPlotArr, 1)
        Workbooks(sWB).Sheets("Output").Range(strIRange).Columns(lngN + 1).Value2 = sngPlotArr(lngN, 0)
        Workbooks(sWB).Sheets("Output").Range(strURange).Columns(lngN + 1).Value2 = sngPlotArr(lngN, 1)
        'give OS some time
        If lngN Mod 100 = 0 Then
            DoEvents
        End If
    Next

    ...

    'relock
    Workbooks(sWB).Sheets("Output").Protect sPW
End Sub

0 个答案:

没有答案