首页 > 解决方案 > Excel vba循环遍历包含第一个字母M的所有工作表

问题描述

我一直在尝试遍历某个表号,我有 20 张以 M 开头的表,例如 M1、M2 等直到 M20,我的问题是我正在循环和写作,而不是只写在M表,我在所有表上写。

Sub CountWSNames()
        Dim I As Long
        Dim xCount As Integer
        For I = 1 To ActiveWorkbook.Sheets.Count
            If Mid(Sheets(I).Name, 1, 1) = "M" Then xCount = xCount + 1

            ThisWorkbook.Worksheets(I).Range("A50") = "V" 'This line must write only to M sheets
        Next
        MsgBox "There are " & CStr(xCount) & " sheets that start with 'M'", vbOKOnly, "KuTools for Excel"
    End Sub

类似于我的一小段代码。

ThisWorkbook.Worksheets(I).Range("A50") = "V"

此行只能影响以 M 开头的工作表上的单元格(“A50”)。

标签: excelvbaexcel-formulaexcel-2010

解决方案


您可以使用每个。

For each sht in ActiveWorkbook.Sheets
    If Mid(sht.Name, 1, 1) = "M" Then 
        xCount = xCount +1
        sht.Range("A50") = "V" 'This line must write only to M sheets
    End if
Next

您需要将两种语法都包装在if.


推荐阅读