我有以下代碼循環不斷復位
Sub Split_data()
' Split_data
Dim iCtr As Long
Dim Total As Long
Dim Iterations As Long
Dim FilePath As String
' Save path for new files
FilePath = "C:\DataFiles"
' Create folder to store files
If FileFolderExists(FilePath) Then
' Delete first row with obsolete data
Rows("1:1").Select
Selection.Delete Shift:=xlUp
Else
MkDir (FilePath)
' Delete first row with obsolete data
Rows("1:1").Select
Selection.Delete Shift:=xlUp
End If
Total = Range("A1", Range("A1").End(xlDown)).Count
Iterations = Application.WorksheetFunction.RoundUp(Total/2, 0)
' Generate the files
For iCtr = 1 To Iterations
Generate_Files iCtr, FilePath
Next iCtr
End Sub
本身工作正常,除了1件事的代碼,我已經完成了我的那一刻For循環,我的櫃檯神祕復位爲1和它不斷循環。
所以,如果我得到5行,它循環3次,iCtr
值應該正常上升,但一旦第3次循環完成,它突然跳回到1並開始全部。
因此,任何人看到ZHY,因爲我已經試過做的時候幾次一步一步,但我找不到它ZHY跳碼的回1
休息,如果它的事項:
Function Generate_Files(iCtr As Long, FilePath As String)
'
' Generates files which contain copied data of first copied x rows after which these rows are deleted
'
' Create variables
Dim wb1 As Excel.Workbook
Dim wb2 As Excel.Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim x As Integer
Dim CurrPath As String
' Stop screen flickering
Application.ScreenUpdating = False
' Initialise variables
Set wb1 = ActiveWorkbook
Set ws1 = Worksheets(1)
' Create new workbook
Set wb2 = Workbooks.Add(1)
wb2.Activate
Sheets(1).Name = "data"
Set ws2 = Worksheets("data")
' Set path of created file
CurrPath = ThisWorkbook.FullName
' Copy data from wb1
wb1.Activate
ws1.Select
Rows("1:2").Select
Selection.Copy
' -!-
' Copy done afterwards to prevent issues with copied values disappearing from copy clipboard while creating new file
' -!-
' Activate wb2
wb2.Activate
ws2.Select
' Paste data in wb2
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
' Remove first x lines from original file
wb1.Activate
Rows("1:2").Select
Selection.Delete Shift:=xlUp
' Save & close wb2
wb2.Activate
ActiveWorkbook.SaveAs ("C:\DataFiles\Split Data" & iCtr)
ActiveWorkbook.Close
Application.ScreenUpdating = True
End Function
Public Function FileFolderExists(strFullPath As String) As Boolean
On Error GoTo EarlyExit
If Not Dir(strFullPath, vbDirectory) = vbNullString Then FileFolderExists = True
EarlyExit:
On Error GoTo 0
End Function
很奇怪。你可以嘗試用For循環中的斷點來看循環開始時'Iterations'是否正確顯示5而不是3,並且它在某種程度上不會改變。唯一的其他解釋是,代碼拋出一些錯誤,並退出沒有任何顯示在第三次迭代 – hnk