在vba中进行逻辑运算

您好我正在尝试做逻辑操作或者,而不是与vba,但我有我的代码的麻烦,它不增加我知道它的值可能(希望)一个简单的修复错误任何帮助将不胜感激价值。

sub logicop () Dim myRange As range Dim rowi As range Dim cell As range Set myRange = Range("A8:F20") 'go into each row of column For Each rowi In myeRange.Rows andfunc = 1 'AND operaton notfunc = 0 'NOT function result1 = 0 result2 = 0 result3 = 0 For Each cell In rowi.Cells 'go into each cell of the rows in rowi If cell.Value = notfunc Then resuslt1 = result1 + 1 End If If cell.Value = andfunc Then resuslt2 = result2 + 1 End If If cell.Value <> andfunc And cell.Value <> notfun Then result3 = result3 + 1 End If Next cell Next result1 = Cells(3,3 ) result2 = Cells(3, 4) result3 = Cells(3,5) End Sub 

正如在评论中指出,有许多拼写错误,将阻止您的代码forms工作。 您可以通过使用Option Explicit来避免这种情况。

这里是你的代码清理版本。 除了在Select Case中添加外,我试图保持与原来的接近

 Option Explicit Sub logicop() Dim wks As Worksheet Dim myRange As Range Dim rowi As Range Dim cell As Range Dim andfunc, notfunc, result1, result2, result3 Set wks = Sheets("Sheet1") Set myRange = wks.Range("A8:F20") 'go into each row of column andfunc = 1 'AND operaton notfunc = 0 'NOT function result1 = 0 result2 = 0 result3 = 0 For Each rowi In myRange.Rows For Each cell In rowi.Cells 'go into each cell of the rows in rowi Select Case cell.Value Case notfunc result1 = result1 + 1 Case andfunc result2 = result2 + 1 Case Else result3 = result3 + 1 End Select Next cell Next rowi 'Output results to specific cells wks.Cells(3, 3).Value = result1 wks.Cells(3, 4).Value = result2 wks.Cells(3, 5).Value = result3 End Sub 

请注意,空单元格将按照写入的方式计为0。 我假设你有在你的范围内的每个单元格的数据,所以不会是一个问题。


示例结果:

在这里输入图像说明


编辑

根据评论,我已经更新了代码来计算哪些行全是0,1或者混合。

 Option Explicit Sub logicop() Dim wks As Worksheet Dim myRange As Range Dim rowi As Range Dim andfunc, notfunc, result1, result2, result3, rowSum Set wks = Sheets("Sheet1") Set myRange = wks.Range("A8:F20") 'go into each row of column andfunc = 1 'AND operaton notfunc = 0 'NOT function result1 = 0 result2 = 0 result3 = 0 For Each rowi In myRange.Rows rowSum = Application.WorksheetFunction.Sum(rowi) Select Case rowSum / rowi.Cells.Count Case notfunc result1 = result1 + 1 Case andfunc result2 = result2 + 1 Case Else result3 = result3 + 1 End Select Next rowi 'Output results to specific cells wks.Cells(3, 3).Value = result1 wks.Cells(3, 4).Value = result2 wks.Cells(3, 5).Value = result3 End Sub 

结果

在这里输入图像说明