Excel VBA:无法理解循环

我的代码可以在下面看到。 我已经设置TacticInputDateInput作为一个范围(它发现过滤后的第一个可见的单元格)。

然后我想要CodeTextBox进入范围TacticInput但只有当它的空。 如果它不是空的,我想偏移2列,然后再试一次,如果这不是空的,我也希望它继续尝试,直到它成功地find一个空单元格,并将其分配给CodeTextBox

DateBox相同:如果DateInput空,则将其input到DateInput ,如果不是,则将其偏移2列,然后重试。

这是我设法得到的代码,但它不工作。 我尝试了很多不同的组合,但我卡住了。 目前它只是replace第一列中的值,它没有find下一个空单元并放在那里。

 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 

首先, If TacticInput = "<>"不testing单元格是不是空白的。 你应该使用isempty来代替:

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

另外,当你执行偏移时,我期望你会得到一个运行时错误。 你也想在那里set一个set ,这样你就可以改变被引用的范围。

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

这不一定需要循环。 相反,您可以使用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 

让我知道你是否需要澄清。

你的问题是你写了If TacticInput = "<>" Then :在这种情况下,TacticInput可能永远不会等于后面的字符<>所在的string。 你可能想写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" 

尝试,

 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