[英]Run time error '6' OverFlow (Excel VBA)
我遇到此錯誤,我要加載成千上萬個csv文件,每次只能加載約數百個文件。 誰能告訴我錯誤在哪里?
Option Explicit
Function ImportData()
Dim wkbCrntWorkBook As Workbook
Dim wkbSourceBook As Workbook
Dim rngSourceRange1 As Range
Dim rngSourceRange2 As Range
Dim rngDestination1 As Range
Dim rngDestination2 As Range
Dim intColumnCount As Integer
Set wkbCrntWorkBook = ActiveWorkbook
Dim SelectedItemNumber As Integer
Dim YesOrNoAnswerToMessageBox As String
Dim Highest As Double
Highest = 0
Dim counter As Integer
Dim h1 As Integer
Dim h2 As Integer
h1 = 1
h2 = 7
Do
SelectedItemNumber = SelectedItemNumber + 1
With Application.FileDialog(msoFileDialogOpen)
.Filters.Clear
.Filters.Add "Command Separated Values", "*.csv", 1
'.Filters.Add "Excel 2007", "*.xlsx; *.xlsm; *.xlsa", 2
'.Filters.Add "Excel 2002-03", "*.xls", 3
.AllowMultiSelect = True
.Show
For SelectedItemNumber = 1 To .SelectedItems.Count
If .SelectedItems.Count > 0 Then
Workbooks.Open .SelectedItems(SelectedItemNumber)
Set wkbSourceBook = ActiveWorkbook
Set rngSourceRange1 = ActiveCell.Offset(1, 0)
Set rngSourceRange2 = ActiveCell.Offset(1, 6)
For counter = 0 To 300
Columns("H:H").NumberFormat = "0.00"
'Highest = Application.WorksheetFunction.Max(Range("H1:H300"))
If Highest <= ActiveCell.Offset(h1, h2).Value Then
Highest = ActiveCell.Offset(h1, h2).Value
End If
h1 = h1 + 1
Next
wkbCrntWorkBook.Activate
Set rngDestination1 = ActiveCell.Offset(1, 0)
Set rngDestination2 = ActiveCell.Offset(1, 1)
ActiveCell.Offset(1, 2).Value = Highest
For intColumnCount = 1 To rngSourceRange1.Columns.Count
If intColumnCount = 1 Then
rngSourceRange1.Columns(intColumnCount).Copy rngDestination1
Else
rngSourceRange1.Columns(intColumnCount).Copy rngDestination1.End(xlDown).End(xlDown).End(xlUp).Offset(1)
End If
Next
For intColumnCount = 1 To rngSourceRange2.Columns.Count
If intColumnCount = 1 Then
rngSourceRange2.Columns(intColumnCount).Copy rngDestination2
Else
rngSourceRange2.Columns(intColumnCount).Copy rngDestination2.End(xlDown).End(xlDown).End(xlUp).Offset(1)
End If
Next
ActiveCell.Offset(1, 0).Select
wkbSourceBook.Close False
End If
Next SelectedItemNumber
End With
YesOrNoAnswerToMessageBox = MsgBox("Continue?", vbYesNo)
Loop While YesOrNoAnswerToMessageBox = vbYes
Set wkbCrntWorkBook = Nothing
Set wkbSourceBook = Nothing
Set rngSourceRange1 = Nothing
Set rngSourceRange2 = Nothing
Set rngDestination1 = Nothing
Set rngDestination2 = Nothing
YesOrNoAnswerToMessageBox = Empty
SelectedItemNumber = Empty
Highest = Empty
counter = Empty
h1 = Empty
h2 = Empty
intColumnCount = Empty
End Function
要從“未回答的問題”列表中刪除此問題,我將以“社區Wiki”樣式回答此問題,以避免將他人的工作視為功勞。
正如Tim Williams在評論中回答的那樣,答案的一部分是使用Long
變量而不是Integer
變量,以確保在進行大量迭代時不會超出允許的變量值。
正如user1828786的最后一條評論所表明的,答案的另一部分是掃描代碼中的邏輯錯誤,以確保針對您進行的每個循環都重置了計數器變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.