Hướng dẫn cách lấy tên các sheet trong excel

Trong một số trường hợp bạn cần lấy tên của các sheet trong file excel, bạn có thể thực hiện thủ công bằng cách copy và paste. Tuy nhiên cách thủ công này khó để mà thực hiện trong trường hợp file excel có quá nhiều sheet.

Bài viết này hướng dẫn cách lấy tên sheet một cách tự động

Lấy tên sheet hiện tại

Nhập công thức sau vào cell mà bạn muốn lấy tên:

=RIGHT(CELL("filename"),LEN(CELL("filename"))-FIND("]",CELL("filename")))

Hoặc dùng 2 hàm

  • lấy tên file: =CELL(“filename”,A1)
  • Sau đấy dùng hàm left hoặc right lấy tên sheet

Lấy tên tất cả các sheets

Nhấn phím tắt Alt+F11 để mở cửa sổ VBA, sau đấy nhấn vào insert tạo module mới, paste đoạn code dưới đây vào. Nhấn Run, toàn bộ tên sheet cùng link tới sheet đó được hiển thị trong sheet hiện hành của bạn

Private Sub CreateTableOfContents()
Dim wsSheet As Worksheet
Dim ws As Worksheet
Dim Counter As Long

On Error Resume Next
Set wsSheet = Sheets("Mucluc")
'Kiem tra su ton tai cua Sheet
On Error GoTo 0
If wsSheet Is Nothing Then
'Neu chua co thi them vao vi tri dau tien cua Workbook
Set wsSheet = ActiveWorkbook.Sheets.Add(Before:=Worksheets(1))
wsSheet.Name = "Mucluc"
End If

With wsSheet
.Cells(2, 1) = "DANH SACH CAC SHEET"
.Cells(2, 1).Name = "Index"
.Cells(4, 1).Value = "STT"
.Cells(4, 2).Value = "Ten Sheet"
End With

'Merge Cell
With Range("A2:B2")
.Merge
.HorizontalAlignment = xlCenter
.Font.Bold = True
End With

'Set ColumnWidth
With Columns("A:A")
.ColumnWidth = 8
.HorizontalAlignment = xlCenter
End With

With Range("A4")
.HorizontalAlignment = xlCenter
.Font.Bold = True
End With

Columns("B:B").ColumnWidth = 30
With Range("B4")
.HorizontalAlignment = xlCenter
.Font.Bold = True
End With

Counter = 1
For Each ws In Worksheets
If ws.Name <> wsSheet.Name Then
'Gan gia tri cot thu tu
wsSheet.Cells(Counter + 4, 1).Value = Counter
'Tao lien ket
wsSheet.Hyperlinks.Add Anchor:=wsSheet.Cells(Counter + 4, 2), _
Address:="", _
SubAddress:=ws.Name & "!A1", _
ScreenTip:=ws.Name, _
TextToDisplay:=ws.Name
'Them nut Quay ve Sheet Muc luc tai moi Sheet
With ws
.Hyperlinks.Add Anchor:=.Range("H1"), Address:="", SubAddress:="Index", TextToDisplay:="Quay ve"
End With
Counter = Counter + 1
End If
Next ws
Set xlSheet = Nothing
End Sub

Facebook Comments