运行时错误91 - 访问excel交互

时间:2014-03-06 14:01:19

标签: excel access-vba

我正在运行访问VBA代码来打开Excel,对某些图表进行微小修改并将其保存为bmps。它运行良好98%的时间。但是,我偶尔会在“Selection.Left = 320”行中收到以下错误:

  

运行时错误'91':
  对象变量或未设置块变量

我想解决的第二个小问题是,每次运行此宏后打开任何其他excel文档时,此宏使用的excel文档也会自动打开,不知道为什么。

Private Sub Form_Open(Cancel As Integer)
If [Forms]![Detail]![Qualification Documents].[Value] <> "" Then
         Dim octopus As String
         octopus = ([Forms]![Detail]![Qualification Documents].[Value])
         Set objExcelApp = New Excel.APPLICATION
         Dim ws As Worksheet

Set wb = objExcelApp.Workbooks.Open(FileName:="Path\" & octopus & " ", ReadOnly:=True)
         'Set ws = wb.Sheets("SheetX")
          wb.APPLICATION.DisplayAlerts = False
          wb.Sheets("SheetX").Select
  x = 1
  While x < 4
  wb.ActiveSheet.ChartObjects(x).Activate
  With wb.ActiveChart.Parent
     .Height = 500 ' resize
     .Width = 1200 ' resize
     .Top = 100    ' reposition
     .Left = 100   ' reposition
  End With

                 On Error GoTo here:
here:
wb.ActiveChart.Legend.Select
Selection.Left = 320
Selection.Top = 380
Selection.Height = 35
Selection.Width = 600
wb.ActiveChart.Export "X:\Assembly\CAPEX 2013\drilling database\graph" & x & ".bmp"
x = x + 1
Wend
wb.Close
Set objExcelApp = Nothing
End If
End Sub

1 个答案:

答案 0 :(得分:0)

似乎Selection不时无效,即在运行宏时,选择在某种程度上无效,例如,用户点击Excel窗口或类似的东西。尝试直接使用图表或对象的Left属性,而不使用Selection.

x = 1
While x < 4
    With wb.Sheets("SheetX").ChartObjects(x)
        .Parent.Height = 500 ' resize
        .Parent.Width = 1200 ' resize
        .Parent.Top = 100    ' reposition
        .Parent.Left = 100   ' reposition

        .Legend.Left = 320
        .Legend.Top = 380
        .Legend.Height = 35
        .Legend.Width = 600
    End With
Wend