Insert tab name for multiple tabs using vba

maomaodang

New Member
Joined
Nov 16, 2018
Messages
6
Hi,

I have 20 excel tabs, which each representing a restaurant outlet. I would like to have the tab name indicating in cell B1 to cell M1 for each tab except this Master tab.

Below is my code:

Sub Insert_Tab_Name()
Dim sht As Worksheet
For Each sht In ActiveWorkbook.Worksheets
If sht.Name <> "Master" Then
Range("B1", "M1").Formula = "=Mid(Cell(""filename"",B1),Find(""]"",Cell(""filename""))+1,255)"
End If
Next sht
End Sub

It works on the active tab, but not for the rest of the tabs ie I have to run the macro 20 times rather than 1 time. Anyone can help to check what's wrong with my formula please? Many thanks!
 

Excel Facts

What does custom number format of ;;; mean?
Three semi-colons will hide the value in the cell. Although most people use white font instead.
Try this.
Code:
Sub Insert_Tab_Name()
Dim sht As Worksheet
    For Each sht In ActiveWorkbook.Worksheets
        If sht.Name <> "Master" Then
            sht.Range("B1", "M1").Formula = "=Mid(Cell(""filename"",B1),Find(""]"",Cell(""filename""))+1,255)"
        End If
    Next sht
End Sub
 
Upvote 0
Thank you so much! It works perfectly now. May I understand how does the sht in front of the Range make it works?
 
Upvote 0
Code:
Sub Insert_Tab_Name()
 Dim sht As Worksheet
  For Each sht In ActiveWorkbook.Worksheets
   If sht.Name <> "Master" Then
    sht.Range("B1", "M1").Value = sht.Name
   End If
  Next sht
End Sub
 
Upvote 0
Without a worksheet reference Range will refer to a range on the active sheet, by changing it to sht.Range it ensures it refers to a range on the sheet that the sheet object variabe sht refers to.
 
Upvote 0

Forum statistics

Threads
1,214,911
Messages
6,122,198
Members
449,072
Latest member
DW Draft

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top