2014-03-03 101 views
2

儘管我的代碼可用於10次循環迭代,但它在home = 30或更多時崩潰。有人可以給我提供一些線索嗎?即使這個代碼很奇怪以前工作得很好......並且不再工作。運行幾分鐘後,Excel VBA腳本會凍結excel

下面的代碼:

Sub datascrap_clean() 

' 

Application.Calculation = xlCalculationManual 
Application.ScreenUpdating = False 

Dim home    As Integer 

Dim output_rows   As Integer 
Dim output_columns  As Integer 
Dim date_columns  As Integer 


'Output rows and columns starting values 
output_rows = 3 
output_columns = 3 
date_columns = 8 

For home = 3 To 33 

    With ActiveSheet.QueryTables.Add(Connection:= _ 
     "URL;http://www.cqc.org.uk/directory/" & Sheets("Output").Cells(home, 1), Destination:=Range("$A$1") _ 
     ) 
     '.CommandType = 0 
     .Name = "Homes" 
     .FieldNames = True 
     .RowNumbers = False 
     .FillAdjacentFormulas = False 
     .PreserveFormatting = True 
     .RefreshOnFileOpen = False 
     .BackgroundQuery = True 
     .RefreshStyle = xlInsertDeleteCells 
     .SavePassword = False 
     .SaveData = True 
     .AdjustColumnWidth = True 
     .RefreshPeriod = 0 
     .WebSelectionType = xlEntirePage 
     .WebFormatting = xlWebFormattingNone 
     .WebPreFormattedTextToColumns = True 
     .WebConsecutiveDelimitersAsOne = True 
     .WebSingleBlockTextImport = False 
     .WebDisableDateRecognition = False 
     .WebDisableRedirections = False 
     .Refresh BackgroundQuery:=False 
    End With 




For x = 20 To 250 
    Select Case Left(Cells(x, 1), 7) 

    'Is it a score? 
    Case Is = "Overall" 

     Sheets("Output").Cells(output_rows, output_columns).Value = Cells(x, 1) 
     output_columns = output_columns + 1 

    'Is it a date? 
    'Case Is = "Carried" 

     ' Sheets("Output").Cells(output_rows, output_columns).Value = Cells(x, 1) 
     'date_columns = date_columns + 1 

    Case Else 

    End Select 

    Sheets(2).Select 

Next x 

    'Clean sheet 
    ActiveSheet.Cells.Delete 

    'Reset column count 
    output_columns = 3 
    date_columns = 8 

output_rows = output_rows + 1 
Next home 



MsgBox ("Done!") 
End Sub 
+0

你能告訴它代碼中哪裏凍結了嗎?放一些站點,然後逐步完成,直到代碼看起來非常有效。 – APrough

+0

這就是事情,它不凍結在一個特定的點: - 對於家庭= 10它不凍結, - 對於家庭= 50它崩潰後一段時間 –

+0

所以,你不能擊中CTRL + Break當它「凍結「並查看它掛起的代碼部分是什麼? – APrough

回答

1

我有同樣的問題,在一個循環中創建的QueryTable對象和Excel的有掛在看似隨機的時間(通常是創造約15的QueryTable對象後)。我注意到,在VBE調試和插入斷點運行時,問題沒有發生。

Application.Wait(Now + TimeValue("0:00:02")) 

能夠成功運行與創建〜300個的QueryTable對象的情況下:那麼,除了使用它們作爲在前面的回答建議後刪除的QueryTable對象,我在循環的開始插入一個短暫的延遲沒有掛。是的,一個雜湊,但它至少提供了一個解決方法。如果沒有延遲,即使在刪除QueryTable對象後,我仍然會掛起Excel。