在Access 2003中使用后期绑定的Excel范围的“未定义的用户定义类型”

时间:2010-07-01 13:02:12

标签: vba access-vba

我正在尝试编写一个VBA脚本,该脚本将文件夹中的所有Excel文件导入到Access 2003中的表中,首先检查它们是否已导入。那部分没问题。我遇到的问题是清除一些未在电子表格上使用的公式,这会导致Access尝试导入范围时出现问题。当按原样运行代码时,我收到错误“用户定义的类型未定义”。

我正在使用后期绑定,因为我正在开发一个使用多个版本的Office的站点,因此无法使用早期绑定引用相同的库。问题代码如下:

Private Sub Command2_Click()
'Declare Variables
Dim xlApp As Object
Dim xlBook As Object
Dim LSQL As String
Dim SkippedCounter As Integer
Dim ImportedCounter As Integer
Dim BUN As Long
Dim SubmitDate As Date
Dim LSQL2 As String
Dim LSQL3 As String

'Start counters for final notice
SkippedCounter = 0
ImportedCounter = 0

Dim myDir As String, fn As String

'Set directory for importing files
myDir = "U:\Five Star\Operations\restore\Surveys\My InnerView - 2010\Action plans\Action plans - input for DB\"

'Function for selecting files in folder
fn = Dir(myDir & "*.xls")

'Determine if there are files in side the folder
If fn = "" Then
    MsgBox "Folder is Empty!"
Else
    'Begin cycling through files in the folder
    Do While fn <> ""
        'Create new Excel Object
        Set xlApp = CreateObject("Excel.Application")
        'Make it appear on the screen while importing
        xlApp.Visible = True
        'Open the workbook at hand
        Set xlBook = xlApp.Workbooks.Open(myDir & fn)
        'Check to see if it has been imported already
        If xlBook.Sheets("Action plan form").Range("A1").Value = "Imported" Then
                'If it has been imported, add 1 to the counter, close the file and close the instance of Excel
                SkippedCounter = SkippedCounter + 1
                xlBook.Close
                xlApp.Quit
                Set xlBook = Nothing
                Set xlApp = Nothing
            Else
                'Otherwise, unprotect the worksheet
                xlBook.UnProtect Password:="2010"
                Dim c As Range
                'Unhide worksheet needed and clean it up
                xlBook.Sheets("Action plan DB data").Visible = True
                xlBook.Sheets("Action plan DB data").Range("B10:O10").ClearFormats
                xlBook.Sheets("Action plan DB data").Range("N11:N84").ClearFormats
                For Each c In xlBook.Sheets("Action plan DB data").Range("DB_import")
                    If c.Value = "" Or c.Value = 0 Then c.Clear
                Next c
                ...

其余的代码应该运行正常,它有一个问题,声明“范围”并循环通过它。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

As Range移除Dim c As Range,这会使c成为对象。这样,当它被延迟到一个范围后,你将不会有任何问题。