VBA-在For循环中打印

时间:2017-06-26 12:30:46

标签: vba excel-vba excel

我正在尝试从多列数据中查找和删除异常值,但在运行代码时,它不会清除包含异常值的单元格。我尝试在第一个For循环中打印“colLength”,这也没有做任何事情。关于我哪里出错或者我怎么能解决它的建议?

Sub Outliers()

Dim calc As Worksheet
Set calc = ThisWorkbook.Sheets("Sheet2")

Dim num As Double
Dim x As Integer
Dim y As Integer
Dim colLength As Integer

'Variables for upper fence, lower fence, first quartile, third quartile, and interquartile range
Dim upper As Double
Dim lower As Double
Dim q1 As Double
Dim q3 As Double
Dim interquartRange As Double

For y = 1 To y = 49

'Find last row of the column
colLength = calc.Cells(Rows.count, y).End(xlUp).Row

'Calculate first and third quartiles
q1 = Application.WorksheetFunction.Quartile(Range(Cells(2, y), Cells(colLength, y)), 1)
q3 = Application.WorksheetFunction.Quartile(Range(Cells(2, y), Cells(colLength, y)), 3)

interquartRange = q3 - q1

'Calculate upper and lower fences
upper = q3 + (1.5 * interquartRange)
lower = q1 - (1.5 * interquartRange)

For x = 2 To x = colLength
    num = calc.Cells(x, y)

    'Remove outliers
    If num > upper Or num < lower Then
        Range(calc.Cells(x, y)).ClearContents
    End If
Next x

Next y

End Sub

1 个答案:

答案 0 :(得分:1)

For y = 1 To y = 49应为For y = 1 To 49。同样,For x = 2 To x = colLength应为For x = 2 To colLength

在新模块中尝试此操作,您将看到并理解其中的差异;)

Dim Y As Long

Sub SampleA()
    For Y = 1 To Y = 49
        Debug.Print Y
    Next Y
End Sub

Sub SampleB()
    For Y = 1 To 49
        Debug.Print Y
    Next Y
End Sub