2

我的 Excel 工作簿中可能有名为 Data1、Data2、...的工作表。我想知道我的工作簿中有多少这样的工作表。

我试图比较工作表名称并保持计数。但它不能正常工作。

所以希望有人可以在这里帮助我。提前致谢。

4

2 回答 2

6

试试这个

msgbox thisworkbook.sheets.count

这将返回工作簿中的工作表数量。

要返回名称如“数据”的工作表数量,请执行以下操作:

Dim iCountSheets As Integer
Dim oSheet As Worksheet
'
For Each oSheet In Sheets
    If oSheet.Name Like "Data*" Then
       iCountSheets = iCountSheets + 1
    End If
Next

MsgBox iCountSheets & " sheets like data"

另一种方法是按索引遍历工作表集合:

Dim iCountSheets As Integer, iIdx As Integer
Dim oSheet As Worksheet
'
For iIdx = 1 To Sheets.Count ' non-zero based collection
    If Sheets(iIdx).Name Like "Data*" Then
       iCountSheets = iCountSheets + 1
    End If
Next

MsgBox iCountSheets & " sheets like data"
于 2013-03-28T13:49:28.153 回答
4

这是你正在尝试的吗?

'~~> Case Sensitive
Sub Sample()
    Dim ws As Worksheet
    Dim shCount As Long

    For Each ws In ThisWorkbook.Sheets
        If ws.Name Like "Data*" Then shCount = shCount + 1
    Next ws

    Debug.Print shCount
End Sub

'~~> Or use the below if you have sheets like data1, Data2, DaTa3 etc
Sub Sample()
    Dim ws As Worksheet
    Dim shCount As Long

    For Each ws In ThisWorkbook.Sheets
        If UCase(ws.Name) Like "DATA*" Then shCount = shCount + 1
    Next ws

    Debug.Print shCount
End Sub
于 2013-03-28T13:49:37.000 回答