首先,我在设置百分位应用程序时遇到问题,不确定如何将其放置为数组和myVar。我看过一些代码,不确定是什么以及为什么要在其中放置某些值。
其次,我希望在行16-79上运行两个不同的百分位计算,每个行彼此唯一。由于范围在工作表之间变化,因此无法设置列。我下面的代码查找包含数据的最后一列并创建2列:其后为“ 20th Percentile”和“ 80th Percentile”。因此,我认为这可用于帮助设置范围。这需要在多张纸上运行。
Sub create_columns_test2()
Dim WS As Worksheet
Dim x As Integer
Dim array(???) As Variant?
'What do I set my array as? why variant?
Dim myVar as Double?
'What does double mean
For Each WS In ActiveWorkbook.Worksheets
With WS
If .Cells.Find("20th Percentile") Is Nothing And _
.Cells.Find("80th Percentile") Is Nothing Then
x = .UsedRange.Columns.Count
.Cells(16, x + 2).Value = "20th Percentile"
myVar = Application.WorksheetFunction.Percentile(Array(16, x - 1), 0.2)
.Cells(16, x + 3).Value = "80th Percentile"
myVar = Application.WorksheetFunction.Percentile(Array(16, x - 2), 0.8)
'I want the percentile to run from rows 16 to 79 individually
'from column C to the column before the matching column I've just created
End If
End With
Next WS
For Each WS In ActiveWorkbook.Worksheets
WS.Range("N:Q").EntireColumn.AutoFit
Next WS
End Sub
检查此解决方案。如果不清楚,请阅读代码中的注释-在注释中提问。首先说明-我不太了解您如何以这种方式使用百分位:
我希望百分位数分别从第16行升至第79行
但是我认为您将能够修复函数的参数。
Sub create_columns_test2()
Dim WS As Worksheet
' give variables proper names - I've used colNo instead of x for column number (see Note 1 in post)
Dim colNo As Long
Dim rowNo As Long
' Don't need this at all
' Dim array(???) As Variant?
' 'What do I set my array as? why variant?
' Dim myVar as Double?
' 'What does double mean
' be careful with using ActiveWorkbook / Sheet (see Note 2 in post)
For Each WS In ActiveWorkbook.Worksheets
With WS
If .Cells.Find("20th Percentile") Is Nothing And _
.Cells.Find("80th Percentile") Is Nothing Then
' using .UsedRange.Columns.Count is very tricky and may
' return incorrect data
colNo = .Cells(1, Columns.Count).End(xlToLeft).Column
' Set column headers - Ok
.Cells(16, colNo + 2).Value = "20th Percentile"
.Cells(16, colNo + 3).Value = "80th Percentile"
'I want the percentile to run from rows 16 to 79 individually
For rowNo = 17 To 79
'from column C to the column before the matching column I've just created
' this part takes data from column C:
.Cells(rowNo, colNo + 2).Value = Application.WorksheetFunction.Percentile(Range(.Cells(rowNo, 3), .Cells(rowNo, colNo)), 0.2)
.Cells(rowNo, colNo + 3).Value = Application.WorksheetFunction.Percentile(Range(.Cells(rowNo, 3), .Cells(rowNo, colNo)), 0.8)
Next
End If
End With
' Don't need separate loop - can do it after each iteration
WS.Range("N:Q").EntireColumn.AutoFit
Next WS
End Sub
注1请参阅Naming Conventions。网络中还有其他一些命名约定,例如“ for vba”,建议使用基于类型名称的前缀,但我个人反对这样做。但总的来说,这些也意味着一件简单的事情-当您在一个月后回到代码中时-您将不会立刻记住该变量x
或y
的含义,但是您肯定会知道colNo
是什么或rowNo
用于。
注2在此处检查this post并决定是否要真正使用ActiveWorkbook
,因为放置代码的工作簿并不总是活动的。