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

我正在运行一个访问VBA代码来打开Excel,对一些图进行小修改并将它们保存为bmp。 这是98%的时间。 但是,我现在每隔一行在“ Selection.Left = 320 ”行出现以下错误:

运行时错误“91”:
对象variables或块variables未设置

我想解决的第二个小问题是,每次运行这个macros后,我打开其他任何一个excel文档,这个macros使用的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 

似乎Selection不时是无效的,即,当运行macros时,select以某种方式失效,例如通过用户点击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