我想创建一个无限循环
do while endOfLoop<>"" OR endOfLoop <> "end"
If endOfLoop = "" Then
Answer = MsgBox("Are you sure you want to quit? If you are done press cancel _
and then type in 'end'")
If Answer = 6 Then
Exit Sub
End If
End If
'request from user to enter a column name
Dim ColumnName & count
count = count + 1
请记住,我现在只是在这个框中编写了这段代码,所以我不知道除了“昏暗的rowname&amp; count”之外其他一切是否正确
但你可以看到,我想要做的是有一个无限的while循环,直到用户输入“end”或取消out每个迭代计数增加的位置并且我声明变量:
ColumnName1
ColumnName2
ColumnName3
...
ColumnName(x)
这可能吗?
编辑:
对于任何希望使用此代码的人来说,这意味着从单元格到单元格激活并将标题读入数组。例如,如果您在单元格(1,1)中,并且标题为First |最后|中间
然后它会创建一个“ColumnNames”数组,直到列中没有填充为止。作为对DCRomley的大喊,我只是想解释一下,当活动Cell的单元格列中没有文本时,while循环将停止,因此除非您填写了无限单元格,否则使用此单元格无法结束无限循环。感谢所有帮助我创建此解决方案的人!此外,如果有人可以帮我重新说这个,这样我就不必在最后加上“count = count-1”条款,那就太棒了。
Do While endOfLoop <> ""
ReDim Preserve ColumnNames(Count)
ColumnNames(Count) = endOfLoop
Count = Count + 1
ActiveCell.Offset(0, 1).Activate
endOfLoop = ActiveCell.Text
Loop
Count = Count - 1
答案 0 :(得分:1)
如果您最后不想要Count = Count - 1
,只需将代码更改为以下内容:
Dim Count As Integer
Dim ColumnNames()
Count = 0
Do While endOfLoop <> ""
Count = Count + 1
ReDim Preserve ColumnNames(Count)
ColumnNames(Count) = endOfLoop
ActiveCell.Offset(0, 1).Activate
endOfLoop = ActiveCell.Text
Loop
这将确保最后的计数是正确的。但是,做这样的事情可能更加清晰(不需要选择单元格)
Sub makeList()
Dim thisRow
Dim headerNames()
Dim listOfNames As String
Dim cc As Integer
cc = 0
Set thisRow = Range(ActiveCell, ActiveCell.End(xlToRight))
For Each c In thisRow
If c.Value = "" Then Exit For
cc = cc + 1
ReDim Preserve headerNames(cc)
headerNames(cc - 1) = c.Value
If cc = 1 Then listOfNames = c.Value Else listOfNames = listOfNames & ", " & c.Value
Next c
MsgBox "there were " & cc & " cells." & vbCrLf & "Their names were " & listOfNames
End Sub
注意 - 即使范围中只有一个单元格,上述内容也会起作用 - 尽管thisRow
最终会指向标题的末尾,Exit For
仍然会在一个单元格之后停止循环迭代。