访问 - 打开Excel文件,用它做一些编码并关闭

时间:2016-03-14 12:58:26

标签: excel vba excel-vba ms-access access-vba

我试图从Access打开Excel文件并用它做一些事情,但代码不稳定。有时候它有效,有时则没有。以下是我如何做到这一点:

 Dim FilePath As String
 Dim ExcelApp As Excel.Application

 FilePath = "C:\Users\Lucky\Desktop\Test.xls"

Set ExcelApp = CreateObject("Excel.Application")

ExcelApp.Workbooks.Open (FilePath)

With ExcelApp

'do some stuff here
End With

ExcelApp.Workbooks.Close

Set ExcelApp = Nothing

我还注意到,一旦我运行代码,Excel就会在任务管理器下启动进程,必须手动终止才能让代码再次运行。否则我会在Excel文件中出现两种类型的错误:

  • 一个是如果我点击Excel文件,它没有打开,只是闪烁一秒钟并且消失了

  • 和其他是Excel文件打开"只读"模式...

所以我认为在我的代码中关闭文件时存在一些缺陷。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

我无法查看您的代码有什么问题 - 也许是通往桌面的路径?
这是我经常使用的代码 - 我已经添加了另一个函数来帮助选择文件。它使用后期绑定,因此无需设置对Excel的引用 - 您没有获得IntelliSense并且无法使用Excel常量,例如xlUp - 您必须使用等效的数字。 / p>

Public Sub Test()

    Dim oXLApp As Object
    Dim oXLWrkBk As Object
    Dim oXLWrkSht As Object
    Dim vFile As Variant
    Dim lLastRow As Long

    vFile = GetFile()

    Set oXLApp = CreateXL
    Set oXLWrkBk = oXLApp.WorkBooks.Open(vFile, False)
    Set oXLWrkSht = oXLWrkBk.WorkSheets(1) 'First sheet.  Can also use "Sheet1", etc...

    lLastRow = oXLWrkSht.Cells(oXLWrkSht.Rows.Count, "A").End(-4162).Row '-4162 = xlUp

    MsgBox "Last row in column A is " & lLastRow

    oXLWrkBk.Close False
    oXLApp.Quit
    Set oXLWrkBk = Nothing
    Set oXLApp = Nothing


End Sub

Public Function CreateXL(Optional bVisible As Boolean = True) As Object

    Dim oTmpXL As Object

    '''''''''''''''''''''''''''''''''''''''''''''''''''''
    'Defer error trapping in case Excel is not running. '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''
    On Error Resume Next
    Set oTmpXL = GetObject(, "Excel.Application")

    '''''''''''''''''''''''''''''''''''''''''''''''''''''''
    'If an error occurs then create an instance of Excel. '
    'Reinstate error handling.                            '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''
    If Err.Number <> 0 Then
        Err.Clear
        On Error GoTo ERROR_HANDLER
        Set oTmpXL = CreateObject("Excel.Application")
    End If

    oTmpXL.Visible = bVisible
    Set CreateXL = oTmpXL

    On Error GoTo 0
    Exit Function

ERROR_HANDLER:
    Select Case Err.Number

        Case Else
            MsgBox "Error " & Err.Number & vbCr & _
                " (" & Err.Description & ") in procedure CreateXL."
            Err.Clear
    End Select

End Function

Function GetFile(Optional startFolder As Variant = -1, Optional sFilterName As String = "") As Variant
    Dim fle As Object
    Dim vItem As Variant

    '''''''''''''''''''''''''''''''''''''''''''
    'Clear the file filter and add a new one. '
    '''''''''''''''''''''''''''''''''''''''''''
    Application.FileDialog(3).Filters.Clear
    Application.FileDialog(3).Filters.Add "'Some File Description' Excel Files", "*.xls, *.xlsx, *.xlsm"

    Set fle = Application.FileDialog(3)
    With fle
        .Title = "Select a file"
        .AllowMultiSelect = False
        If startFolder = -1 Then
            .InitialFileName = CurrentProject.Path
        Else
            If Right(startFolder, 1) <> "\" Then
                .InitialFileName = startFolder & "\"
            Else
                .InitialFileName = startFolder
            End If
        End If
        If .Show <> -1 Then GoTo NextCode
        vItem = .SelectedItems(1)
    End With
NextCode:
    GetFile = vItem
    Set fle = Nothing
End Function

答案 1 :(得分:0)

我设法解决了我的问题。我的问题中的代码没有任何问题,除了不是声明

Dim ExcelApp As Excel.Application

使用

更好
Dim ExcelApp As Object

但更大的问题是在Excel中执行更改的代码,例如此行:

x = Range(Cells(1, i), Cells(Rows.Count, i).End(xlUp)).Value

正确的synthax是:

x = ExcelApp.Range(ExcelApp.Cells(1, i), ExcelApp.Cells(ExcelApp.Rows.Count, i).End(xlUp)).Value 'maybe also better to replace xlUp with -4162

因此,每当您从Access使用Excel文件的某些代码时,请不要将所有内容引用到Excel对象。当然,在所有事情之前,必须在VBA控制台中设置适当的引用,在我的情况下是Microsoft Office 15.0库。