2016-03-23 233 views
0

我遇到了從Access中循環瀏覽Excel文件的麻煩。這裏是我的代碼:訪問VBa - 通過Excel列循環

 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 

無論我做什麼,我總是得到一個錯誤,在這條線:

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

或者這一個:

For i = 2 To UBound(x) 

錯誤是「對象不支持此屬性或方法「或」對象變量或未設置塊變量「。我該如何解決這個問題,有沒有人有線索?

+0

如果在該行中找不到搜索值,則會得到對象變量錯誤。 – Rory

+0

但是。在第一行中,我有名爲「Število」的專欄。我忘了提及 - 這段代碼正常工作了2周,現在突然它不... – LuckyLuke82

+0

是否:'我= XcelApp.Match(「Število」,XcelApp.Rows(1),0)'工作? – Rory

回答

0

我已經manged得到它的工作:

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 

我不得不從代碼中刪除ExcelBook,現在它工作正常。