使用VBA在Excel公式参数中指定单元格地址

我有一列和B列,他们比较他们以前的价值和IAM比较它与下面的公式

=IF((OR(AND(A2=A1,B2=B1),K2=0),0,1) it puts the 0 or 1 on the coresponding Q column 

所以当它进入第五个单元格时,它就成了

  =IF((OR(AND(A5=A4,B5=B4),K5=0),0,1) 

但即时通讯尝试将其应用于我的VBA代码,如这些

  For numm = 2 To lastRow Sheet1.Cells(numm, "Q").Value = ="IF(OR(AND(sheet1.cells(numm,""A"").value=sheet1.cells(numm-1,""A"")simlar way becolumn),sheet1.cells(numm,""k"").value=0),1,0)" Next numm 

但我无法执行的行动,它说1004错误和对象错误如何在我的VBA公式中使用单元格(numm,“A”)或至less有任何其他方式来把我的公式,使其工作

公式中对循环numm的引用需要超出string。

也许你可以在VBA中设置单元格公式本身…

 For numm = 2 To lastRow Sheet1.Cells("Q" & numm).Formula = _ "=IF((OR(AND(A" & numm & "=A" & numm - 1 & ",B" & numm & _ "=B" & numm - 1 & "),K" & numm & "=0),0,1)" Next numm 

就个人而言,我会在VBA(ifs,ors和ands)中完成整个语句,然后把值放回到Excel中。 使用Excel公式使代码难以阅读。

你在找什么东西吗?

 Public Sub test() Dim Sheet1 As Excel.Worksheet Set Sheet1 = ActiveSheet Dim numm As Integer, lastrow As Integer lastrow = 5 For numm = 2 To lastrow Sheet1.Cells(numm, "Q").Value = "=IF(OR(AND(" & Sheet1.Cells(numm, "A").Address & "=" & Sheet1.Cells(numm - 1, "A").Address & "," & Sheet1.Cells(numm, "B").Address & "=" & Sheet1.Cells(numm - 1, "B").Address & ")," & Sheet1.Cells(numm, "k").Address & "=0),1,0)" Next numm End Sub 

Sheet1不能被引用到单元格的值中,它只存在于你创build的vba函数中,所以你可以把string附加到一起,然后把单元格地址取出来以匹配你所在的函数创造更早。