如何使用vba计算工作表中的单元格数

时间:2012-10-09 17:31:55

标签: excel-vba vba excel

我是Vba的新手,我有5张不同的纸张,名为1到5张,第1张纸有一个按钮和标签,所以我想选择纸张3中的所有内容,当我按下按钮时我想让它显示我的号码我在Label中选择的单元格

Sub Button2_Click()

Dim rngCell As Range, arrArray() As Variant, i As Integer

ReDim arrArray(1 To Selection.Cells.Count)

i = 1
For Each rngCell In Selection

    arrArray(i) = rngCell.Value
    i = i + 1

Next

ActiveSheet.Shapes("Label 1").Select
Selection.Characters.Text = i


End Sub

2 个答案:

答案 0 :(得分:1)

我认为这比你想象的要简单得多......

Option Explicit

Sub CaptureSelectionCount()

' Keyboard Shortcut: Ctrl+Shift+E '-> adjust to make sure this doesn't overwrite an existing function in your workbook
Dim lngCnt as Long

lngCnt = ActiveSheet.Selection.Cells.Count

Sheets("Sheet1").Shapes("Label 1").TextFrame.Characters.Text = lngCnt

End Sub

答案 1 :(得分:0)

这样做会但是这不是一种非常优雅的做事方式 - 我看不到任何替代方案。您需要利用事件来捕获先前选择的工作表。由于确定工作表上选择范围的唯一方法是激活该工作表,您必须关闭屏幕更新跳转到工作表,然后跳回原始工作表并重新打开屏幕更新。

将以下代码放入新模块中:     选项明确

'Global variables (avoid using globals if you can)
Public wsLast As Worksheet
Public iSelectedCells As Integer

'Link this sub to your button
Public Sub CountCells()
    If Not wsLast Is Nothing Then
        Sheets("Sheet1").Shapes("Label 1").TextFrame.Characters.Text = "There " & IIf(iSelectedCells = 1, " is " & iSelectedCells & " cell selected ", " are " & iSelectedCells & " cells selected ") & "in " & wsLast.Name
    End If
End Sub

以下代码需要放入电子表格的“ThisWorkbook”模块中:

Option Explicit

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
    Dim wsThisWorksheet As Worksheet

    'Turn off events to avoid triggering a loop
    Application.EnableEvents = False

    'Set this worksheet so we can come back to it
    Set wsThisWorksheet = ActiveSheet

    'Record the deactivated sheet as a global variable
    Set wsLast = Sh

    'Turn off screen updating, go back to the last sheet, count the selection
    Application.ScreenUpdating = False
    wsLast.Activate
    iSelectedCells = Selection.Cells.Count

    'Then come back to the original and turn screen updating back on
    wsThisWorksheet.Activate
    Application.ScreenUpdating = True

    'Restore events
    Application.EnableEvents = True

    'Set the local variable to nothing
    Set wsThisWorksheet = Nothing
End Sub

您可以通过检查是否使用按钮停用工作表来进一步增强代码,如果是,则忽略它。