Excel VBA循环问题

时间:2015-07-07 14:38:21

标签: excel vba excel-vba

我正在编写一个以输入有效日期开始的宏。在日期输入之后,我希望宏在工作表中搜索具有此日期的所有行。然后,我想要为这些行总计所有相应的信用和借记,然后我希望将这些总数放入另一个工作表中。这是我为此编写的代码。

问题是EVENTUALLY,代码将在“Search =,If和End If”中无限循环。如果我在结束之前放置一个“Else:Next I”,那么我会收到一个错误,Else没有For提示。

有什么建议吗?

pat="^(lo){3}(l[^o]|[^l].)"

1 个答案:

答案 0 :(得分:2)

使用已使用的范围而不是10000

    Dim lROw as Long
    Do While lRow <= ws.UsedRange.Rows.Count

        'Do stuff here.

        lRow = lRow + 1
        ws.Range("A" & lRow).Activate
    Loop

所以你的代码看起来像这样

Private Sub CommandButton3_Click()

Dim dateCheck As String
Dim lastRow As Long
Dim L As Integer
Dim I As Long
Dim shipDay As Date
Dim search As String
Dim usaTotal As Long
Dim usaCredit As Long
Dim usaDebit As Long

dateCheck = InputBox("What Date is Ship Day 1?", "Ship Day Entry")

If IsDate(dateCheck) Then
    shipDay = DateValue(dateCheck)
Else:
    MsgBox ("Invalid Date")
    Exit Sub
End If ' Prompts user for ship day 1, and checks if actual date

For L = 0 To 30  ' Execute this code for 1 month worth of dates

shipDay = shipDay + L

MsgBox shipDay

    I = 1
    Do While I <= ws.UsedRange.Rows.Count
        search = Worksheets("sheet1").Cells(I, 12).Value  ' Variable to use InStr to check for "CAN"

        If ((InStr(1, search, "CAN", vbBinaryCompare) = 0) _
            And (Worksheets("Sheet1").Cells(I, 8) = shipDay) _
            And (Worksheets("Sheet1").Cells(I, 6).Text = "Invoice")) Then

            usaDebit = Worksheets("Sheet1").Cells(I, 22).Value ' Account for   Debits
            usaCredit = Worksheets("Sheet1").Cells(I, 24).Value ' Account  for Credits
            usaTotal = usaTotal + usaCredit - usaDebit  ' Calculate contribution

            ' This is where I tried placing an Else: Next I, which gives me an else without for prompts.
        elseif instr(something, something) then

        End If

        I = I + 1
        ws.Range("A" & I).Activate
    Loop

MsgBox (usaTotal)
Worksheets("JUNE canada").Cells(L + 10, 4).Value = usaTotal / 1000  'Enter value into sheet
usaTotal = 0    ' Reset usaTotal value

Next L