简体   繁体   English

访问-打开Excel文件,使用它进行一些编码,然后关闭

[英]Access - open Excel file, do some coding with It and close

I'm trying to open an Excel file from Access and do some stuff with It, but code is not stable. 我正在尝试从Access打开一个Excel文件并对其进行一些处理,但是代码不稳定。 Sometimes It works, other times not. 有时它可以工作,而其他时候则不行。 Here's how I do this: 这是我的操作方式:

 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

I've also noticed that once I run code, Excel starts proccess under Task Manager, that has to be killed manually in order to get code working again. 我还注意到,一旦我运行代码,Excel就会在任务管理器下启动进程,必须手动将其杀死才能使代码重新工作。 Otherwise I get two types of error with Excel file: 否则,Excel文件会出现两种错误:

  • one is that If I click Excel file, It doesn't open, It just flashes for a second and dissapears 一个是如果我单击Excel文件,它不会打开,它会闪烁一秒钟并消失

  • and other is that Excel file opens in "read-only" mode... 另一个是Excel文件以“只读”模式打开...

So I reckon there is some flaw when file is closed in my code. 因此,我认为在代码中关闭文件时存在一些缺陷。 How can I fix this ? 我怎样才能解决这个问题 ?

I can't see what's wrong with your code - maybe the path to the desktop? 我看不到您的代码有什么问题-也许是桌面的路径?
This is the code I usually use - I've added another function to help choose the file. 这是我通常使用的代码-我添加了另一个功能来帮助选择文件。 It uses late binding, so no need to set a reference to Excel - you don't get the IntelliSense and can't use Excel constants such as xlUp - you have to use the numerical equivalent. 它使用后期绑定,因此无需设置对Excel的引用-您不会获得IntelliSense,也不能使用Excel常量(例如xlUp -您必须使用数值等效项。

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

I have managed to solve my problem. 我设法解决了我的问题。 There is nothing wrong with code in my question, except that instead of declaring 我的问题中的代码没有什么问题,除了声明之外

Dim ExcelApp As Excel.Application

It's better to use 最好用

Dim ExcelApp As Object

But much bigger problem is with code that does changes in Excel, such as this line: 但是更大的问题是代码会在Excel中进行更改,例如以下行:

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

And correct synthax is: 正确的合成音是:

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

So, whenever you use some code for Excel file from Access, DON'T FORGET to reference everything to Excel object. 因此,每当您对Access中的Excel文件使用一些代码时,请不要忘记将所有内容都引用到Excel对象。 And ofcourse, before everything, a proper reference must be set in VBA console, in my case Microsoft Office 15.0 library. 当然,在一切之前,必须在VBA控制台(在我的情况下为Microsoft Office 15.0库)中设置适当的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM