在vba中进行逻辑运算

时间:2016-09-12 21:44:17

标签: excel vba excel-vba macros

您好我正在尝试逻辑操作OR,NOT,和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

1 个答案:

答案 0 :(得分:3)

正如评论中指出的那样,有许多拼写错误会阻止您的代码形式起作用。您可以使用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。我假设你的范围内的每个单元都有数据,所以不会有问题。

示例结果:

enter image description here

修改

根据评论,我已更新代码以计算哪些行全部为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

<强>结果

enter image description here