Excel VBA:无法理解循环

时间:2014-12-15 15:04:37

标签: excel vba loops

我的代码如下所示。 我已将TacticInputDateInput设置为范围(它会在过滤后找到第一个可见的单元格)。

然后,我希望它将CodeTextBox输入范围TacticInput,但前提是它为空。 如果它不是空的我想要偏移2列,然后再试一次,如果那不是空的,我希望它继续尝试,直到它成功找到一个空单元并将其分配给CodeTextBox

DateBox相同:如果其为空,则输入DateInput,如果不为,则将其输入2列,然后重试并重复。

这是我设法提出的代码,但它不起作用。我尝试了很多不同的组合,但我被卡住了。 目前它只是替换第一列中的值,它找不到下一个空单元格并将其放在那里。

Dim TacticInput As Range
Dim DateInput As Range
Dim TrueValue As Boolean

Set TacticInput = Sheets("Sheet1").Range([B2], Cells(Rows.Count, "AL")).SpecialCells(xlCellTypeVisible)(1)
Set DateInput = Sheets("Sheet1").Range([C2], Cells(Rows.Count, "AL")).SpecialCells(xlCellTypeVisible)(1)


TrueValue = False
Do Until TrueValue = True
    If TacticInput = "<>" Then
        TacticInput.Offset(0, 2) = TacticInput
        DateInput.Offset(0, 2) = DateInput
    Else
        TacticInput = CodeTextBox.Value
        DateInput = DateBox.Value
        TrueValue = True
    End If
Loop

4 个答案:

答案 0 :(得分:0)

你不一定需要一个循环。相反,您可以使用Find来获取该范围内的最后一个可用空单元格,然后使用它来定义应该写入值的单元格。例如:

Sub test()

    Dim rInput As Range
    Dim LastCol As Long

    Set rInput = Sheets("Sheet1").Range([B2], Cells(Rows.Count, "AL")).SpecialCells(xlCellTypeVisible)
    LastCol = rInput.Rows(1).Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

    If LastCol Mod 2 = 0 Then
        LastCol = LastCol + 2
    Else
        LastCol = LastCol + 1
    End If

    Cells(rInput.Cells(1, 1).Row, LastCol).Value = CodeTextBox.Value
    Cells(rInput.Cells(1, 1).Row, (LastCol + 1)).Value = DateBox.Value

End Sub

如果您需要澄清,请告诉我。

答案 1 :(得分:0)

首先,If TacticInput = "<>"不测试单元格是否为空白。您应该使用isempty代替:

If not isempty(TacticInput.Offset(0, i)) Then

此外,当您执行偏移时,我希望您会收到运行时错误。您还需要set,以便更改要引用的范围。

If TacticInput = "<>" Then
    Set TacticInput = TacticInput.Offset(0, 2)
    Set DateInput = DateInput.Offset(0, 2)

答案 2 :(得分:0)

你的问题是你写了If TacticInput = "<>" Then:在这种情况下,TacticInput可能永远不会等于一个字符串,其中跟随字符&lt;&gt;位于。你可能想写If TacticInput = "",这与If TacticInput <> ""

非常相反

您可以尝试一个非常简单的循环:

i = 0

Do Until IsEmpty(YourRange.Offset(i,0))
    i = i + 2
Loop

YourRange.Offset(i,0) = "Write what you want here"

答案 3 :(得分:-3)

尝试,

Dim i as long
TrueValue = False
i = 0

Do Until TrueValue = True
    If TacticInput.Offset(0, i) Is Nothing Then
        TacticInput.Offset(0, i) = CodeTextBox.Value
        DateInput.Offset(0, i) = DateBox.Value
        TrueValue = True
    Else
        i = i + 2
    End If
Loop
相关问题