VBA COUNTA用户表单

时间:2019-02-23 16:37:03

标签: excel vba if-statement countif

我有一个带有几个文本框和一个命令按钮的用户窗体。输入并提交信息后,信息将转移到第一行。

我需要一个可以在该行的4列内counta()文本的代码。因此,请在用户提交信息后将=IF(IsBlank($A2),"",COUNTA(E2:H2)转换为VBA代码以进行计算。

2 个答案:

答案 0 :(得分:0)

假设我们正在使用Sheet1 并假设您的行号已存储在 ThisRowNum变量

关注应该接近您的要求

    If Trim(CStr(Sheets("Sheet1").Range("A" & ThisRowNum).Value)) = "" then
       xCtr = 0  ' Your formula used a null string - you can fix this
    else
       xCtr = WorksheetFunction.CountA(Sheets("Sheet1").Range("E" & ThisRowNum &":H" & ThisRowNum))
    endif

xCtr变量是结果

答案 1 :(得分:0)

enter image description here

Option Explicit

Sub test()
    Debug.Print "Var 1 : "; CountRangeIf("not(A3="""")", Range("E3:H3"))

    Dim testCriteria As Boolean
    testCriteria = Not (Range("A3").Value = "")
    Debug.Print "Var 2 : "; CountRangeIf_Var2(testCriteria, Range("E3:H3"))
End Sub

Public Function CountRangeIf(IfCriteriaString As String, CountRange As Range) As Variant
    Dim resultCriteria As Boolean
    CountRangeIf = ""           ' Result = "" if Criteria is false
    resultCriteria = Evaluate(IfCriteriaString)
    With Application.WorksheetFunction
        If resultCriteria Then
            CountRangeIf = .CountA(CountRange)
        End If
    End With
End Function

Public Function CountRangeIf_Var2(IfCriteria As Boolean, CountRange As Range) As Variant
    CountRangeIf_Var2 = ""           ' Result = "" if Criteria is false
    With Application.WorksheetFunction
        If IfCriteria Then
            CountRangeIf_Var2 = .CountA(CountRange)
        End If
    End With
End Function