在MS Access中运行Excel宏时出现运行时错误

时间:2016-07-06 04:29:26

标签: excel-vba vba excel

这是我的第一篇文章,我对编程很陌生。

我目前停留在一行代码中,这些代码在构建Graph时停止运行。 基本上我有一个数据库/访问,我有一个功能,我单击按钮,它打开一个特定位置的文件。然后打开Excel并开始运行我的代码,然后暂停。

下面是一个片段,它被卡在下面一行

ActiveChart.Axes(xlValue,xlPrimary).AxisTitle.Text =“每月M³”

Range("A2:M6").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLine
ActiveChart.SetSourceData Source:=Range("LCLSPENDGRAPH!$A$2:$M$6")
ActiveChart.SetElement (msoElementDataTableShow)
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleRotated)
ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Text = "M³ Per Month"
Selection.Format.TextFrame2.TextRange.Characters.Text = "M³ Per Month"
With Selection.Format.TextFrame2.TextRange.Characters(1, 11).ParagraphFormat
    .TextDirection = msoTextDirectionLeftToRight
    .Alignment = msoAlignCenter
End With
With Selection.Format.TextFrame2.TextRange.Characters(1, 11).Font
    .BaselineOffset = 0
    .Bold = msoTrue
    .NameComplexScript = "+mn-cs"
    .NameFarEast = "+mn-ea"
    .Fill.Visible = msoTrue
    .Fill.ForeColor.RGB = RGB(0, 0, 0)
    .Fill.Transparency = 0
    .Fill.Solid
    .Size = 10
    .Italic = msoFalse
    .Kerning = 12
    .Name = "+mn-lt"
    .UnderlineStyle = msoNoUnderline
    .Strike = msoNoStrike

`

任何建议都将不胜感激。

亲切的问候 JDogg

1 个答案:

答案 0 :(得分:0)

如果要从Access控制Excel,则基本上有2个选项。请尝试下面的2个脚本,并回复其他问题......

‘EARLY BINDING
Option Compare Database
Option Explicit ' Use this to make sure your variables are defined

' One way to be able to use these objects throughout the Module is to Declare them
' Here and not in a Sub

Private objExcel As Excel.Application
Private xlWB As Excel.Workbook
Private xlWS As Excel.Worksheet

Sub Rep()

Dim strFile As String

strFile = "C:\Users\Excel\Desktop\YourExcelFile.xls"

' Opens Excel and makes it Visible
Set objExcel = New Excel.Application
objExcel.Visible = True

'Opens up the Workbook
Set xlWB = objExcel.Workbooks.Open(strFile)

'Sets the Workseet to the last active sheet - Better to use the commented version and use the name of the sheet.
Set xlWS = xlWB.ActiveSheet
'Set xlWS = xlWB("Sheet2")

With xlWS ' You are now working with the Named file and the named worksheet


End With

'Do Close and Cleanup
End Sub


 
‘LATE BINDING
Sub ControlExcelFromAccess()

' No reference to a type library is needed to use late binding.
' As long as the object supports IDispatch, the method can
' be dynamically located and invoked at run-time.

' Declare the object as a late-bound object
  Dim oExcel As Object
  Dim strFile As String

  strFile = "C:\Users\Excel\Desktop\YourExcelFile.xls"

  Set oExcel = CreateObject("Excel.Application")

' The Visible property is called via IDispatch
  oExcel.Visible = True

  Set xlWB = oExcel.Workbooks.Open(strFile)

'Call Ron's code here . . .

Set oExcel = Nothing

End Sub