2016-09-14 51 views
0

我有一些数据,看起来像这样:循环在一定范围内,逐行

enter image description here

对于标有“优惠券”我想,如果他们加入这一行中的数字,该项目的所有行非空白。如果它们是空白的,我想让它们独自一人。另外,如果单元格中的数据碰巧是日期,我不想触摸它。

逐行我想贯穿整个范围。

我目前的代码给我一个“对于每个可能只能迭代集合对象或数组vba”错误。请帮忙!

Sub CommandButton1_Click() 


Dim rng As Range 
Dim rw As Range 
Dim cel As Range 


Set rng = Range("E15:P464") 

For Each rw In rng.Row 
    If rw.Item(1, 1) = "coupon" Then 
     For Each cel In rw.Cells 
      If IsEmpty(cel.Value) = False Then 
        If Not IsDate(cel) Then 
         cel.Value = cel.Value + 0.0001 
        End If 
      End If 
     Next cel 
    End If 
Next rw 



End Sub 
+1

你想'rng.Rows'与s –

+1

你会还需要'rw.Cells(1,1)'而不是'rw.Item(1,1)'。项目会给出一个“应用程序定义或对象定义的错误”。 –

+0

@chrisneilsen Thx。将它更改为行后,我得到“运行时错误1004:应用程序定义或对象定义的错误” – Amatya

回答

1

克里斯·尼尔森给的解决方案来修复错误

你可能要采取的替代AutoFilter()方法,如下所示:

Option Explicit 

Sub main() 
    Dim cel As Range 

    With Worksheets("Coupons") '<--| reference "Coupons" worksheet (change "Coupons" to your actual worksheet name) 
     With .Range("A1").CurrentRegion '<--| reference its range made of cells contiguous to "A1" 
      .AutoFilter Field:=1, Criteria1:="Coupon" '<--| filter it on column "A" with "Coupon" criteria 
      If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then '<--| if any "Coupon" in column A" has been filtered 
       For Each cel In .Offset(1, 1).Resize(.rows.Count - 1, .Columns.Count - 1).SpecialCells(xlCellTypeVisible).SpecialCells(XlCellType.xlCellTypeConstants, xlNumbers) '<-- loop through filtered range cells containing numbers (and skipping column "A" and row 1) 
        If Not IsDate(cel) Then cel.Value = cel.Value + 0.0001 ' update non-date numbers 
       Next cel 
      End If 
     End With 
     .AutoFilterMode = False '<--| show all rows back 
    End With 
End Sub 
+0

感谢您向我展示了一种完全不同的方法,这种方法可能更加高效和多样。 – Amatya

1

尝试下面的代码,它比你张贴的一个稍有不同:

Sub CommandButton1_Click() 

Dim rng   As Range 
Dim rw   As Range 
Dim Col   As Long 
Dim CellStr  As String 

Set rng = Range("E15:P464") 

' loop through rows in Range 
For Each rw In rng.Rows 
    ' get the value of the first column and convert to String 
    CellStr = rw.Columns(1).Value 

    ' use StrComp to verify match between strings 
    If StrComp(CellStr, "coupun") = 0 Then 

     ' loop through all columns in current row (where there was a match with "coupun" 
     For Col = rng.Columns(2).Column To rw.Columns.Count 

      ' check if current cell is empty 
      If Not IsEmpty(Cells(rw.Row, Col)) Then 
       If Not IsDate(Cells(rw.Row, Col)) Then 
        Cells(rw.Row, Col).Value = Cells(rw.Row, Col).Value + 0.0001 
       End If 
      End If 
     Next Col 

    End If 
Next rw 

End Sub 
+1

注意_coupun _... – user3598756

+0

@ user3598756不遵循......你的意思是什么_coupun_? –

+0

应该是“优惠券”的那个::-) – user3598756