For循环Excel VBA中的变量限制

时间:2019-03-19 14:36:01

标签: excel vba

是否可以在实际更改变量的for循环中设置变量限制?像这样

Set sht = Worksheets(2)

For i = 1 To sht.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
    [instructions that may or may not insert new rows]
Next i

对于我来说,在for循环中,数据范围可能只会增加,但仍然需要遍历所有内容。

换句话说,每次迭代都会更新上限吗?

5 个答案:

答案 0 :(得分:0)

This is a task for a Do While/Until Loop rather than a For Next. Assuming your rows are inserted below the current one:

currentRow = 1 '<-- or wherever your row starts
Do While Cells(currentRow, yourColumn) <> "" '<-- assuming your "stop" is the first empty row, as I understand for how you define the upper bound of your loop
    '[maybe insert a row]
    currentRow = currentRow + 1 '<-- increase the current row to scan the next one (if you inserted a row just below, it will be the one you just inserted). 
Loop

Just as a rule of thumb, For Next loops are designed for lengths that you know before starting the loop, while Do While/Until loops are designed for lengths that you don't know before you start the loop.

答案 1 :(得分:0)

这是所有行的循环。如果当前行是第1列中最后使用的行,它将停止:

Private Sub LoopOverAllNewRows()
    Dim sht As Worksheet
    Dim i As Long

    Set sht = Worksheets(2)
    i = 0
    Do
       i = i + 1
       ' [instructions that may or may not insert new rows]
       ' If SomethingWentWrong Then Exit Do
    Loop Until i = sht.Cells(sht.Rows.Count, 1).End(xlUp).Row
End Sub

为防止尾部循环,您可能需要插入其他Exit Do条件。

答案 2 :(得分:0)

下一个循环

VBA帮助

For counter = start To end

Next [counter]

一项小型研究

以下是我看到For Next循环工作的方式。有些陈述至少是不正确的,而且可能并非完全正确。

Sub ForNext()
    Dim i as Long
    For i = 1 to 3
        Msgbox i
    Next ' or Next i
    Msgbox "You might have thought that 'i' is '3' now, but it isn't. It is '" & i & "'". 
End Sub

以下两项不能更改:

start = 1
end = 3

第一轮:
start(1)被写入counter(i = 1)。
Msgbox显示counter(i = 1)。
Next增加counter(i = 2)。
针对counter(3)检查end(i = 2)。
如果counter(i = 2)<= end(3)( TRUE ),请转到下一轮,否则退出( FALSE >)。
第二轮:
counter是2(i = 2)。
Msgbox显示counter(i = 2)。
Next增加counter(i = 3)。
针对counter(3)检查end(i = 3)。
如果counter(i = 3)<= end(3)( TRUE ),请转到下一轮,否则退出( FALSE >)。
第三轮:
counter是3(i = 3)。
Msgbox显示counter(i = 3)。
Next增加counter(i = 4)。
针对counter(3)检查end(i = 4)。
如果counter(i = 4)<= end(3)( FALSE ),请转到下一轮,否则退出( TRUE >)。
退出
外部Msgbox显示counter(i = 4)。

两件重要的事情
循环将运行end - start + 1次(轮)。
counter最终将是end + 1

这并不总是正确的,例如如果将i = 5000放入循环,则counter(i)最终等于5001。
如果将i = i - 1放入循环,则将导致无限循环:counter将始终为1。
如果将i = i-2放入循环,循环将一直运行,直到超过变量的值限制并结束“溢出”错误。

最后,一旦循环开始(start已写入counter),它就“忘记了” start,所以{{ 1}}可以小于counter
但是start将是“相关的”,直到退出循环为止,循环将在end大于counter(或使用end)时发生。

答案 3 :(得分:0)

程序的逻辑可能告诉您要遍历现有行。在这种情况下,我建议您使用For Each循环:

Dim varRow As Variant: For Each varRow In sht.UsedRange.Rows
    If varRow.Row = 2 Or varRow.Row = 5 Then
        varRow.EntireRow.Insert XlInsertShiftDirection.xlShiftDown, False ' Insert row above this
        varRow.offsert(1, 0).EntireRow.Insert XlInsertShiftDirection.xlShiftDown, False ' Insert row below this
    End If
    Debug.Print varRow.Address
Next varRow

我测试了代码,它一直运行到最后一行。

答案 4 :(得分:-1)

插入行联合专长。联合范围交流发电机

由于“可能插入或不插入新行的指令”之谜尚未揭晓,所以我想出了自己的“指令”。

说明

浏览工作表中已使用的行,并检查当前行号是否在列表(数组)中,并在找到的行之前(上方)插入一行。

代码

      <OutputClaims>
            <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="Verified.Email" Required="true" />
            <OutputClaim ClaimTypeReferenceId="objectId" />
            <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
            <OutputClaim ClaimTypeReferenceId="authenticationSource" />
           <OutputClaim ClaimTypeReferenceId="strongAuthenticationPhoneNumber" />
    </OutputClaims>

备注

  • 例如,如果使用Sub InsertRowsUnion() Dim sht As Worksheet ' Source Worksheet Dim rngU As Range ' Union Range Dim vnt As Variant ' Value Array Dim i As Long ' Source Worksheet Row Counter Dim URA As Long ' Union Range Alternator ' Create an array of values. vnt = Array(5, 6, 12, 17) Set sht = Worksheets(2) ' Loop through rows of Source Worksheet. For i = 1 To sht.Cells.Find("*", , xlFormulas, , xlByRows, xlPrevious).Row ' Check if current row can be found in Value Array. If Not IsError(Application.Match(i, vnt, 0)) Then ' Check if Union Range already contains a range. If Not rngU Is Nothing Then ' Already CONTAINS a range. URA = URA Mod 2 + 1 ' Add cell at the intersection of current row and ' column URA (1 or 2, "A" or "B") and 'renew' the reference ' to Union Range. Set rngU = Union(rngU, sht.Cells(i, URA)) Else ' Does NOT contain a range. Only the first time. ' Add cell at the intersection of current row and ' column 2 ("B") and create a reference to Union Range. Set rngU = sht.Cells(i, 2) End If End If Next ' Debug.Print rngU.Address ' Check if Union Range contains a range. If Not rngU Is Nothing Then ' Insert rows. rngU.EntireRow.Insert ' .Hidden = True , .Delete End If End Sub Union Range Alternator),两个(或更多) 连续的单元格(行)被添加到URAUnion将 将其翻译为Union和两个连续的行将是 插入第二行之前,而我们想在第二行之前添加一行 第二排,第三排之前的另一排。不需要A2:A3 (降低效率),如果使用URAHidden代替 Delete
  • 如果要在找到的单元格(行)之后(下方)插入行,请在两行Insert中将Set rngU替换为i