面对excel中每个循环的问题

时间:2015-05-05 10:19:32

标签: excel vba excel-vba

enter image description here我正在使用VBA。 我循环遍历每一行,列匹配值,我得到G列的值与选定的行。

  Dim selectedCell As Range
    Dim weekMinutes As Double
    Dim rowNumber As Integer

    usageTracking.Activate
    weeklySheetName = sheetName

     For Each selectedCell In ActiveSheet.Range("A:A")
      If selectedCell.Value = customerName Then
'          weekMinutes = ActiveSheet.Range("G" & (selectedCell.row)).Value
           weekMinutes = Cells(selectedCell.row, "G").Value
End If

  Next selectedCell

我能够获得第一行的价值。 从第二排,即使我有不同的价值," weekMinutes"值显示为0而不是单元格中的值。

我做错了什么。

2 个答案:

答案 0 :(得分:1)

在不知道你的数据的情况下,我告诉你我担心的问题是:customerName

For Each selectedCell In ActiveSheet.Range("A:A")
    If selectedCell.Value = customerName Then '<-- customerName is something, I hope...
        weekMinutes = Cells(selectedCell.row, "G").Value
    End If
Next selectedCell '<-- we are to the next cell...

...但是customerName从未改变过......它总是与你进入循环的值相同。

我猜你错过了这个变量的重新分配?至于您提供的代码,似乎唯一的标准可能决定weekMinutes的值来改变循环。

此外,我想让你观察weekMinutes是否(可能)连续分配但从未使用过;当循环遍历范围的这些单元格时,您将始终覆盖该值,并且您将仅保留在最后一次迭代中获得的值;这真的是你的意思吗?

答案 1 :(得分:0)

 Dim customerName As String
 Dim sheetName As Worksheet
 Dim dataFound As Boolean

 Dim selectedCell As Range
 Dim weekMinutes As Double

 Set sheetName = Sheets(ActiveSheet.Name)
 customerName = sheetName.Range("A" & (ActiveCell.Row)).Value
 dataFound = False

 For Each selectedCell In sheetName.Range("A1:A1000")
 If UCase(selectedCell.Value) = UCase(customerName) Then
 weekMinutes = sheetName.Range("G" & selectedCell.Row).Value