Access VBa - loop through Excel columns

我只是一个虾纸丫 提交于 2019-12-11 23:28:11

问题


I'm having troubles with looping through Excel file from Access. Here is my code:

     Sub Xceltest()

        Dim XcelApp As Object
        Dim XcelBook As Excel.Workbook
        Dim x, i
        Set XcelApp = CreateObject("Excel.Application")
        XcelApp.ScreenUpdating = False

Set XcelBook = XcelApp.Workbooks.Open("C:\Users\Lucky\Desktop\Test\Sample.xlsx")

   With XcelBook

i = XcelApp.Rows(1).Find(What:="Število", LookIn:=xlValues, Lookat:=xlWhole).Column

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

        For i = 2 To UBound(x)
            If Not IsNumeric(x(i, 1)) Then

            ExcelApp.Quit
            Set ExcelApp = Nothing
            MsgBox "This Excel file is not valid"
        : Exit Sub

            End If

        Next i

        End With

        XcelApp.Quit
        XcelApp = Nothing

        End Sub

Whatever I do, I always get an error in this line:

i = XcelApp.Rows(1).Find(What:="Število", LookIn:=xlValues, Lookat:=xlWhole).Column

or this one:

 For i = 2 To UBound(x)

Errors are "object doesn't support this property or method" or "object variable or with block variable not set". How can I fix this, does anybody have a clue ??


回答1:


I have manged to get It working:

 Sub Xceltest()

        Dim XcelApp As Object

        Dim x, i
        Set XcelApp = CreateObject("Excel.Application")
        XcelApp.ScreenUpdating = False

        XcelApp.Workbooks.Open("C:\Users\Lucky\Desktop\Test\Sample.xlsx")

   With XcelApp

i = XcelApp.Rows(1).Find(What:="Število", LookIn:=xlValues, Lookat:=xlWhole).Column

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

        For i = 2 To UBound(x)
            If Not IsNumeric(x(i, 1)) Then

            ExcelApp.Quit
            Set ExcelApp = Nothing
            MsgBox "This Excel file is not valid"
        : Exit Sub

            End If

        Next i

        End With

        XcelApp.Quit
        XcelApp = Nothing

        End Sub

I just had to remove ExcelBook from code, now It works fine.



来源:https://stackoverflow.com/questions/36176471/access-vba-loop-through-excel-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!