在Access VBA中使用的Excel应用程序属性

问题描述 投票:0回答:1

我想生成并格式化excel工作簿。文件的创建很容易,但我对格式很困难。

文件创建Dim strCurrentDBName As String

strCurrentDBName = CurrentDb.Name
For i = Len(strCurrentDBName) To 1 Step -1
   If Mid(strCurrentDBName, i, 1) = "\" Then
      strPath = Left(strCurrentDBName, i)
      Exit For
   End If
Next
xlsxPath = strPath & "Report.xlsx"

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Report", xlsxPath, True

MsgBox ("Report generated. " & xlsxPath)

格式

Dim xl As Object
'This deals with Excel already being open or not
On Error Resume Next
Set xl = GetObject(, "Excel.Application")
On Error GoTo 0
If xl Is Nothing Then
  Set xl = CreateObject("Excel.Application")
End If

Set XlBook = GetObject(xlsxPath)
'filename is the string with the link to the file ("C:/....blahblah.xls")

'Make sure excel is visible on the screen
xl.Visible = True
XlBook.Windows(1).Visible = True
'xl.ActiveWindow.Zoom = 75

'Define the sheet in the Workbook as XlSheet
Set xlsheet1 = XlBook.Worksheets(1)

'Format
With xlsheet1
    xlsheet1.Rows("1:1").Select

这是我的错误(运行时错误'1004':应用程序定义或对象定义的错误)

    xlsheet1.Range(xl.Selection, xl.Selection.End(xlDown)).Select
    xlsheet1.Selection.EntireRow.AutoFit

End With
excel vba excel-vba ms-access access-vba
1个回答
1
投票

您正在使用xlDown枚举值,该值需要引用Microsoft Excel对象库。由于您正在使用后期绑定,因此可能未设置该引用。

使用xlDown,-4121的值解决它:

xlsheet1.Range(xl.Selection, xl.Selection.End(-4121)).Select

请注意,如果您将Option Explicit放在模块顶部,则会更容易发现此错误。

© www.soinside.com 2019 - 2024. All rights reserved.