2016-09-14 75 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