我想在桌面上打开一个 Excel 文件并对标题进行一些格式更改。
当我尝试声明对象时,Excel.Application 的智能感知未显示。我认为这意味着我的代码将无法工作。
Sub OpenReviewFile()
'Opens the reviewed file and formats the headers
Dim objExcel As Excel.Application '<= when I type in this line of
code the intellisence doesn't work
...
我在参考中选择了 Microsoft Office 16.0 对象库。
我检查了 Access 中的选项,没有发现任何可能导致此问题的原因。
我编写了更多代码并尝试运行:
'Opens the reviewed file and formats the headers
Sub OpenReviewFile()
'Opens the reviewed file and formats the headers
Dim objExcel As Excel.Application
Dim objbook As Excel.Workbook
Dim objsheet As Excel.Worksheet
Dim objRange As Excel.Range
Dim intCol As Integer
'Open Excel, Open the Reviewed file, Go to the Sheet in the excel
file
Set objExcel = CreateObject("Excel.Application")
Set objbook =
objExcel.Workbooks.Open("C:\Users\cash10\Desktop\IBC_RECS_VS_HPMS.xlsx")
Set objsheet = objbook.Worksheets("EXPORT_TABLE")
For intCol = 1 To 11
Set objRange = objsheet.Cell(1, intCol)
Debug.Print objRange.Value
Next
...
End Sub
我得到编译错误:
用户自定义类型未定义
Tools->References->Microsoft Excel 16.0 Object Library
的引用才能运行以下代码。Playground
标记的区域。如果您不理解前后所有代码也没关系。Option Compare Database
Option Explicit
Sub OpenReviewFile()
Const ProcName As String = "OpenReviewFile"
' Use a boolean to see if it was successful!
Dim IsSuccess As Boolean
' Start an error-handling routine.
On Error GoTo ClearError
' Either:
' Reference a new instance of Excel.
Dim xlApp As Excel.Application: Set xlApp = New Excel.Application
' Or:
' Reference an existing instance of Excel.
'Dim xlApp As Excel.Application: Set xlApp = GetObject(, "Excel.Application")
' Out-comment the line 'If Not xlApp Is Nothing Then xlApp.Quit'
' so it stays open!
xlApp.Visible = True ' out-comment when done testing
'''''''''''
' The Playground
Dim wb As Workbook: Set wb = xlApp.Workbooks.Open( _
"C:\Users\cash10\Desktop\IBC_RECS_VS_HPMS.xlsx")
Dim ws As Worksheet: Set ws = wb.Worksheets("EXPORT_TABLE")
Dim cell As Range, Col As Long
For Col = 1 To 11
Set cell = ws.Cells(1, Col)
Debug.Print cell.Value
Next Col
''''''''''
IsSuccess = True
ProcExit:
On Error Resume Next ' prevent endless loop
' Close the workbook without saving (when just reading).
If Not wb Is Nothing Then wb.Close SaveChanges:=False
' Quit the instance of Excel.
If Not xlApp Is Nothing Then xlApp.Quit
If IsSuccess Then
MsgBox "Success.", vbInformation
Else
MsgBox "Something went wrong.", vbCritical
End If
On Error GoTo 0
Exit Sub
' Continue error-handling routine.
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume ProcExit
End Sub