Excel VBA 中的 While 循环问题
我正在尝试编写一个 VBA 宏,它逐行获取给定列中的单元格值,并组装一个 SQL 查询供我复制粘贴。它基本上将文本片段和变量放在一个单元格中。该查询需要卡号和序数作为输入,因此需要变量。
宏几乎准备就绪,但它陷入了无限的 While 循环。
Sub Query()
Dim Row As Integer
Row = 8
Dim Cardnumber As String
Cardnumber = Range("D" & Row)
Dim Number As Integer
Number = 1
Range("E30").Select
ActiveCell.Value = "SELECT cardnumber, first_name || ' ' || last_name FROM ( SELECT cardnumber, first_name, last_name, c.OrderNo FROM ag_cardholder ch, (SELECT '%" & Cardnumber & "%' cardmask, " & Number & " OrderNo from dual "
While IsNull(Cardnumber) = False
Row = Row + 1
Number = Number + 1
Cardnumber = Range("D" & Row)
ActiveCell.Value = ActiveCell.Value & "UNION ALL SELECT '%" & Cardnumber & "%', " & Number & " OrderNo from dual "
Wend
ActiveCell.Value = ActiveCell.Value & ") c WHERE ch.cardnumber LIKE c.cardmask ORDER BY c.OrderNo ) t"
End Sub
我尝试过 IsEmpty() 而不是 IsNull(),结果是相同的。请让我知道我在这里缺少什么。另外,请随时给我任何使代码更优雅的建议,因为这是我第一次尝试 VBA。预先感谢您的努力。
I'm trying to write a VBA macro that takes the cell values in a given column, row by row, and assembles an SQL query for me to copypaste. It basically puts together text snippets and variables in a cell. The query needs cardnumbers and ordinal numbers as input, hence the variables.
The macro is almost ready, but it gets stuck in an infinite While loop.
Sub Query()
Dim Row As Integer
Row = 8
Dim Cardnumber As String
Cardnumber = Range("D" & Row)
Dim Number As Integer
Number = 1
Range("E30").Select
ActiveCell.Value = "SELECT cardnumber, first_name || ' ' || last_name FROM ( SELECT cardnumber, first_name, last_name, c.OrderNo FROM ag_cardholder ch, (SELECT '%" & Cardnumber & "%' cardmask, " & Number & " OrderNo from dual "
While IsNull(Cardnumber) = False
Row = Row + 1
Number = Number + 1
Cardnumber = Range("D" & Row)
ActiveCell.Value = ActiveCell.Value & "UNION ALL SELECT '%" & Cardnumber & "%', " & Number & " OrderNo from dual "
Wend
ActiveCell.Value = ActiveCell.Value & ") c WHERE ch.cardnumber LIKE c.cardmask ORDER BY c.OrderNo ) t"
End Sub
I've tried IsEmpty() instead of IsNull(), the result is the same. Please let me know what I'm missing here. Also, feel free to give me any advice for making the code more elegant as this is my first try at VBA. Thank you in advance for your efforts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为
String
,Cardnumber
永远不会是Null
或Empty
。它的长度只能为零,Len(Cardnumber) = 0
。如果
Cardnumber
为Variant
,您可以使用IsEmpty
来测试单元格值是否为空。使用
IsNull
是没有意义的,因为 Excel 中的单元格值永远不会Null
。即使从数据库中获取Null
,Excel 也会将其替换为Empty
。回答你的下一个问题:我会将该代码重构为:
Being a
String
,Cardnumber
will never beNull
orEmpty
. It can only have zero length,Len(Cardnumber) = 0
.If
Cardnumber
wasVariant
, you could useIsEmpty
to test if a cell value is blank.There is no point to use
IsNull
, as a cell value in Excel is neverNull
. Even if aNull
is fetched from a database, Excel will replace it withEmpty
.Responding to your next question: I would refactor that code to: