循环通过一列

时间:2015-04-30 17:22:29

标签: excel vba excel-vba

我正在尝试使用VBA循环遍历excel中的列,遇到问题,因为函数中有“W2”硬编码,因此当我遍历电子表格时,W2需要更改为W3,W4 W5等。

下面是我的代码。

Function GetTopDrTS(L_NumCellsFromEdge As Integer, L_NumOfCells As Integer) As Double
  'Get Top Drive Side Triple Spot calculation

  Dim val As Double
  val = 0

  'Select Cell W2 to set starting position
  Range("W2").Select

  'Read in the cells we need to average
  Dim i As Integer
  For i = 0 To L_NumOfCells - 1
    val = val + Selection.Worksheet.Cells(Selection.Row, _
                Selection.Column + EdgePos + L_NumCellsFromEdge + i).Value
  Next i

  GetTopDrTS = val / L_NumOfCells

end function

2 个答案:

答案 0 :(得分:1)

我不确定你为什么需要循环。您的函数只是计算平均值,因此请使用Average函数。这会将您的功能降低到一行:

Function GetTopDrTS(L_NumCellsFromEdge As Integer, L_NumOfCells As Integer) As Double

    GetTopDrTS = WorksheetFunction.Average(Range("W2:W" & L_NumOfCells + 1))

End Function

现在它只是一行,我完全摆脱了这个功能,只需在你通常称之为GetTopDrTS的任何地方使用WorksheetFunction。

请注意,从问题或代码中不清楚EdgePosL_NumCellsFromEdge应该是什么 - 如果它们打算替换硬编码列“W”,它会相当容易用偏移替换它。

答案 1 :(得分:0)

试试这个:

  'Read in the cells we need to average
  Dim i As Integer
  For i = 0 To L_NumOfCells - 1
    range("W" & i).select
    val = val + Selection.Worksheet.Cells(Selection.Row, _
                Selection.Column + EdgePos + L_NumCellsFromEdge + i).Value
  Next i