0

我是 Vba 的新手,我有 5 个不同的工作表,名为工作表 1 到 5,第一个工作表有一个按钮和标签,所以我想选择工作表 3 中的所有内容,当我按下按钮时,我希望它显示单元格的数量我在标签中选择

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
4

2 回答 2

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
于 2012-10-09T17:58:06.337 回答
0

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

将以下代码放入新模块中: Option Explicit

'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

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

于 2012-10-11T11:13:24.173 回答