VBA代码可动态搜索工作表并添加单元格

时间:2018-10-18 15:49:24

标签: excel vba

Sub CountLarge()
    Sheets("Data").Select
    Dim myNum As Integer
    Dim cell As Range
    Dim rngFullRange As Range
    Dim nLarge As Integer

    Do
        myNum = Application.InputBox("Enter a number")
        If myNum = "" Then Exit Sub
    Loop Until myNum > 0 And myNum < 210

    With Range(“A1”)
        Range(.Offset(1, 0), .End(xlDown).End(xlToRight)).Name = 
“dynamicRange”
    End With

    Set rngFullRange = wsData.Range(“dynamicRange”)

    For Each cell In rngFullRange
        If cell.Value > myNum Then
            nLarge = nLarge + cell.Value
        End If
    Next

    MsgBox (nLarge)
End Sub

这是我的代码,我需要它遍历工作表中的每个值(数据从A2开始并覆盖整个工作表,因此我设置了动态范围),并将所有大于用户输入值的值加起来并显示在一个消息框。当我运行该程序时,我可以输入一个数字,但最后没有显示消息框。

**注意:我已经使用您的反馈来编辑代码,当前错误在With Range(“ A1”)行中。该范围适合工作表,因此我对为什么感到困惑,数据从A2开始并填充了工作表的其余部分,这就是为什么我使用此范围。

2 个答案:

答案 0 :(得分:0)

您要将“ mynum”设置为msgbox的值,然后测试“ myvalue”并退出子程序。

将myvalue更改为mynum,您应该已经全部设置

答案 1 :(得分:0)

@Chronocidal说:

=SUMIF(Sheet1!$A$1:$HA$609,">50",Sheet1!$A$1:$HA$609)

或很长一段路要走:

使用FIND在工作表上查找所有值,然后将小于所需数量的数字相加。

该函数将如下所示,尽管您可能希望更改With wrkSht.Cells以仅查看填充的单元格范围:

Public Function CountLarge(StartNumber As Double, Target As Range) As Double

    Dim wrkSht As Worksheet
    Dim myNum As Double
    Dim sFirstAddress As String
    Dim rFound As Range
    Dim dSum As Double

    Set wrkSht = Target.Parent

    With wrkSht.Cells
        Set rFound = .Find("*", , xlValues, xlWhole, , xlNext)
        If Not rFound Is Nothing Then
            sFirstAddress = rFound.Address
            Do
                If IsNumeric(rFound) Then
                    If rFound >= StartNumber Then
                        dSum = dSum + rFound
                    End If
                End If

                'Set rFound = .FindNext(rFound) 'Doesn't work if in a UDF.
                Set rFound = .Find("*", rFound, xlValues, xlWhole, , xlNext) 'Works in a UDF.

            Loop While rFound.Address <> sFirstAddress
        End If
    End With

    CountLarge = dSum

End Function  

然后您可以直接在单元格中调用此命令,例如:

=CountLarge(50,Sheet1!$A$1)  

或您可以使用以下命令在另一个子集中调用它:

Public Sub Test()

    Dim myNum As Double

    myNum = Application.InputBox("Enter a number:", Type:=1)

    MsgBox "Final sum: " & CountLarge(myNum, Sheet1.Range("A1"))

End Sub  

您可以将工作表引用更改为仅文本字符串:

MsgBox "Final sum: " & CountLarge(myNum, "Sheet1")   

为此,您必须将函数参数更改为:

Public Function CountLarge(StartNumber As Double, SheetName as String) As Double  

并将工作表设置为:

Set wrkSht = ThisWorkbook.Worksheets(SheetName)