运行时错误'9':生成电子表格时下标超出范围

时间:2019-08-13 06:58:27

标签: excel vba

我目前正在尝试使用访问数据库,该数据库使用vba生成Excel电子表格和AutoCAD图形;我没有编写代码,也没有使用这种语言编写代码的经验。生成Excel文件时,代码到达MyXL.Parent.Windows(1).Visible = True行,它给出了错误。 excel文件已生成,但与模板相同。

文件名和目录名是占位符

Dim MyXL As Object

    FileCopy "\Directory\Template", "\Directory\Filename"
    ' This copies an Excel file, first half, then renames it with the Sales order number
    Set MyXL = GetObject("\Directory\Template")
    ' This opens the Excel file named in the upper code second half
    MyXL.Application.Visible = True
    MyXL.Application.WindowState = 3
          '  MyXL1.Activate
    MyXL.Parent.Windows(1).Visible = True
    MyXL.Parent.ActiveWindow.WindowState = 2

    With MyXL.Worksheets(1)

    End With

这时它以.Range("T60").Value = Me![Text516]

的形式设置了很多值(我假设)
   MyXL.Worksheets(1).Activate
    MyXL.Save
MyXL.Parent.Quit ' This is what you have to do to close the Application
'MyXL.Parent.Quit
   ' MyXL.Parent.ActiveWindow.WindowState = xlMinimized
'    MyXL.Close

可能的重复项与复制excel电子表格有关,但是此问题远不止于此

编辑:我犯了一个错误,以前有Set MyXL = GetObject("\SameDirectory\SameFilename")行,但实际上是Set MyXL = GetObject("\Directory\Template")

1 个答案:

答案 0 :(得分:0)

打开Excel工作簿,进行编辑并保存为新名称的工作代码示例。

Sub CopyExcel()
Dim xl As Excel.Application, xlw As Excel.Workbook
Set xl = CreateObject("Excel.Application")
'the following two lines have same result
Set xlw = xl.Workbooks.Open("C:\Users\June\MyStuff\Condos.xlsx", , True)
'Set xlw1 = xl.Workbooks.Add("C:\Users\June\MyStuff\Condos.xlsx")
'code to edit 
xlw.SaveAs "C:\Users\June\MyStuff\Condos2.xlsx"
xl.Quit
End Sub