Excel VB For循环不会遍历if语句
我很欣赏这是一个业余问题,但我不习惯VB和它的语法。
我试图根据数量(QTY)列中是否有值来将信息从一个工作表(ProductList)拖到另一个(Quote)。
这是我的方法:
Private Sub cmdProductListContinue_Click() 'Declare variabless Dim i, duration, qty, outputX, outputY 'Set initial values duration = 120 'Used to determine number of iterations in for loop (no. of QTY cells we are to check) i = 3 'Used as cell co-ordinates to pull information from outputX = 17 'Used as cell co-ordinates to output information 'Populate invoice with product info by iterating through all QTY cells and pulling across info if needed For i = 3 To duration 'Reset quantity to zero each time qty = 0 'Set quantity to the value in the QTY cell Set qty = Worksheets("ProductList").Cells(i, 3) 'If there is a quantity value present If qty > 0 Then 'Insert quantity value into appropriate cell in quote sheet Worksheets("Quote").Cells(outputX, 2) = qty 'Insert description into quote sheet Worksheets("Quote").Cells(outputX, 3) = Worksheets("ProductList").Cells(i, 2) 'Insert unit price into quote sheet Worksheets("Quote").Cells(outputX, 4) = Worksheets("ProductList").Cells(i, 4) 'Increment the output co-ordinates to the next line outputX = outputX + 1 End If Next i 'Open quote sheet Sheets("Quote").Select End Sub
使用断点我可以看到,当有一个数量值时,它成功地移动到第一个“Then”语句,但似乎只是返回到循环的开始,完全丢失了其他两个输出行。
我的语法正确吗? 我在逻辑中错过了什么?
我很欣赏这可能很难通过没有工作表来查看数据列等等
“i”设置为3,因为“数量”列中的第一个值位于单元格C中,3“C”中的描述为“2”,而“C”中的价格为“4”。 这些通过循环递增。
任何帮助,这将不胜感激。
谢谢!!
在这里,你将数量分配给一个对象 (一个范围):
Set qty = Worksheets("ProductList").Cells(i, 3)
如果您想要获取单元格值,请使用:
qty = Worksheets("ProductList").Cells(i, 3).Value
分配一个对象时使用“Set”,所以在这里你不需要它。 “价值”是默认的财产,但我宁愿包括它。
你的代码稍作修改:
Private Sub cmdProductListContinue_Click() Dim i, duration, qty, outputX Dim wsQuote As Worksheet, wsProd As Worksheet Set wsQuote = Worksheets("Quote") Set wsProd = Worksheets("ProductList") duration = 120 outputX = 17 For i = 3 To duration qty = wsProd.Cells(i, 3).Value If qty > 0 Then With wsQuote.Rows(outputX) .Cells(2).Value = qty .Cells(3).Value = wsProd.Cells(i, 2).Value .Cells(4).Value = wsProd.Cells(i, 4).Value outputX = outputX + 1 End With End If Next i wsQuote.Activate End Sub
Set qty = Worksheets("ProductList").Cells(i, i)
这个! 将遍历表的对angular线,就像C3,D4,E5等
你可能想要类似的东西
Set qty = Worksheets("ProductList").Cells(i, 3)
要么
Set qty = Worksheets("ProductList").Cells(3, i)
另请检查ProductList表单的其他参考(行尾):
'Insert description into quote sheet Worksheets("Quote").Cells(outputX, outputY + 1) = Worksheets("ProductList").Cells(i, i - 1) 'Insert unit price into quote sheet Worksheets("Quote").Cells(outputX, outputY + 2) = Worksheets("ProductList").Cells(i, i + 1)