2012-10-09 50 views
0

對於Vba來說我是新的,我有5個不同的工作表,名爲工作表1到5,第一個工作表有一個按鈕和標籤,所以我想選擇工作表3中的所有內容,按我希望它告訴我,我在一個標籤如何使用vba對工作表中的單元格數進行計數

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 

回答

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 
+0

它給我這個錯誤「對象不支持此屬性或方法」 –

+0

@MrMashabela - >查看我的編輯。它現在工作嗎? –

+0

它仍然給我同樣的錯誤,它突出顯示這個「lngCnt = Selection.Cells.Count」黃色 –

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 

你可以進一步提高該代碼通過檢查是否使用按鈕取消激活工作表,如果是,則忽略它。

相關問題