2017-08-16 86 views
0

我有一個Access數據庫來打開,編輯和保存Excel文檔,第一次運行時工作正常,但如果我嘗試修改多個文件(或同一文件兩次)「運行時錯誤'1004'失敗:對象'_Global'的方法'單元格'失敗」訪問VBA以打開,編輯和保存Excel文檔

如果我關閉數據庫然後重新打開它,它再次適用於第一個文件改變。

儘管我對VBA並不陌生,但我會說我是新手。這裏是我正在使用的代碼snippit:

Code: 
     'Open spreadsheet and make it visible 
     Set xl = CreateObject("Excel.Application") 
     strInputFile = varItem 
     xl.Workbooks.Open strInputFile 
     xl.Visible = True 

     'Trying to get row count here but not working yet 
     'Set myRange = xl.Sheets("Sheet1").Range("C:C") 
     'lRowCount = Excel.Application.WorksheetFunction.CountA("Sheet1").Range("C:C") 
     'lRowCount = xl.WorksheetFunction.CountA(Worksheets("Sheet1").Cells(C, C)) 
     'Debug.Print lRowCount 
     'strMyRange = "C:C" 
     'lRowCount = xl.WorksheetFunction.CountA(strMyRange) 
     'Debug.Print lRowCount 
     'lRowCount = Excel.Application.WorksheetFunction.CountA(Workbooks(strInputFile).Sheets("Sheet1").Range("C:C")) 
     'Debug.Print lRowCount 

     'Make the changes 
     j = 0 
     If Left(strFile, 4) = "xxxx" Then 
      myPath = "\\a\path\for\xxxx" 
      If InStr(1, strFile, "IQ") Then 
       For i = 1 To 500 'Row count not working yet 
        If InStr(1, Cells(i, "C").Value, myVariable) > 0 Then 
         Cells(i, "B") = "New Value" 
         j = j + 1 
        End If 
       Next 
      End If 
     End If 

'Clean up 
xl.Quit 
Set xl = Nothing 
Set objInputFile = Nothing 
+0

在該行的執行失敗? –

+0

If InStr(1,Cells(i,「C」)。Value,myVariable)> 0 Then – JDH

+1

坦率地說,我不知道它爲什麼可以工作。看起來這個代碼是從Excel複製的。在像Cell這樣的Access直接調用應該不起作用。使用變量,如'xl.Sheets(「Sheet1」)。Cells(i,「C」)' –

回答

1

Excel中使用的Excel VBA代碼應該被修改。您不能使用直接調用Excel庫方法,如Cell。爲Excel.Application,Workbook和Worksheet聲明變量並將其用於引用工作表單元格。避免使用激活方法。所以,在你的情況下,代碼將是這樣的:

Dim xl As Excel.Application 
Dim wb As Excel.Workbook 
Dim ws As Excel.Worksheet 
Dim lRowCount As Long 

Dim myRange As Excel.Range 

Set xl = CreateObject("Excel.Application") 
strInputFile = varItem 
Set wb = xl.Workbooks.Open(strInputFile) 
Set ws = wb.Sheets("Sheet1") 

lRowCount = ws.UsedRange.Rows.Count 
'Make the changes 
j = 0 
If Left(strFile, 4) = "xxxx" Then 
    myPath = "\\a\path\for\xxxx" 
    If InStr(1, strFile, "IQ") Then 
     For i = 1 To lRowCount 
      If InStr(1, ws.Cells(i, "C").Value, myVariable) > 0 Then 
       ws.Cells(i, "B") = "New Value" 
       j = j + 1 
      End If 
     Next 
    End If 
End If 

wb.Save 
'Clean up 
xl.Quit 
Set xl = Nothing 

不要忘記添加一個引用到Microsoft Excel庫

+0

再次謝謝謝爾蓋!這隻適用於一個小變化。我必須在Set wb = xl.Workbooks.Open(strInputFile)中放置()這個變量。沒有什麼大不了的,但是想提一下這個帖子的潛在未來觀衆。 我也點擊了這個答案的向上箭頭,但因爲我是這個網站的新品顯然我的選票還沒有算。 :-) – JDH

+0

是的,當然()需要在這裏,我編輯了答案。如果答案爲您工作,接受它,在投票櫃檯下方會顯示一個綠色的複選標記 –