Excel 2010 VBA循环如果然后声明

VBA新手,但努力学习。 我最近写了一个macros观与IF Then Else在工作的女人。 不幸的是,她不像计算机般聪明,也不想在列表中findmacros,所以我想我会使用一个命令button的用户窗体,并调整代码来循环通过单元格,而不是她从活动单元格到活动细胞。 不幸的是,我在“每个循环中都有If If Else”问题。

这是原始的非循环编码macros

Sub InvoicesTotalDue() Dim myRange As Range Set myRange = Application.InputBox(Prompt:="Select an Invoice Type Then Hit Enter", Type:=8) 'person is on active cell and selects cell in Type column of corresponding row of active cell If myRange.Cells.Value = "Cancel300" Then ActiveCell.Value = 300 ElseIf myRange.Cells.Value = "Cancel350" Then ActiveCell.Value = 350 Else ActiveCell.FormulaR1C1 = "=Product(100,[@Hours])" End If End Sub 

这是工作,但用户发现它乏味,她不习惯使用macros。 所以我想到一个用户表单命令button,通过范围循环,并在最后一列填写相应的值将是她最好的。 这是我认为它应该工作的方式。

 Sub InvoicesTotalDue() Dim myRange As Range Set myRange = Application.Range("Invoices[Type]") For each cCell in myRange If myRange.Cells.Value = "Cancel300" Then [TotalDue].Cell.Value = 300 ElseIf myRange.Cells.Value = "Cancel350" Then [TotalDue].Cell.Value= 350 Else [TotalDue].Cell.FormulaR1C1 = "=Product(100,[@Hours])" End If Next cCell End Sub 

应根据发票types计算总计到期日。 取消是设定的值,任何不取消是100的产品和工作的小时数。

任何人都可以发现我的问题或有任何build议/解决scheme?

谢谢!

尝试:

 For Each cCell in myRange.Cells If cCell.Value = ... 

未经testing,但想迅速把它抛出。

看起来你正在使用表,这是伟大的。 但是,我不认为你需要VBA来解决这个问题。 在“TotalDue”列中,在一个单元格的公式栏中input以下公式:

 =IF([@Type]="Cancel300",300,IF([@Type]="Cancel350",350,100*[@Hours])) 

它应该自动填写整个列。 就像我喜欢VBA,有时候一个公式是一个更好的答案!

但是,我正在运行你的代码,你的问题是这行:myRange.Cells.Value

 If myRange.Cells.Value = "Cancel300" Then 

这是一个不好的参考。 改变它说这个:

 If cCell.Value = "Cancel300" Then 

另一个有用的debugging工具是在vba行之后添加一个MyNewlyDefinedRange.Select,所以我知道它实际上是在我认为我所说的范围内工作的。