使用VBA在Excel中检查工作表

时间:2013-03-28 13:40:15

标签: excel excel-vba vba

我的excel工作簿中可能有Sheets,名为Data1,Data2,... 我想知道的是我的工作簿中有多少这样的表格。

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

所以希望有人可以帮助我。提前谢谢。

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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