使用 Excel VBA 获取工作表名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19323343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:52:59  来源:igfitidea点击:

Get a worksheet name using Excel VBA

excelexcel-vbavba

提问by user2103670

I would like to create an user-definedfunction in Excelthat can return the current worksheet. I could use the

我想创建一个可以返回当前工作表的user-defined函数Excel。我可以使用

sheetname = ActiveSheet.Name

But the problem with this is, it works and suddenly it starts to get different sheet name. For example, instead of SHEET I LOVE YOUit returns SHEET I HATE YOU.

但问题是,它起作用了,突然间它开始得到不同的工作表名称。例如,而不是SHEET I LOVE YOU它返回SHEET I HATE YOU.

Is there anyway to fix this - or it might possible because I think it can not be static but varies?

有没有办法解决这个问题 - 或者有可能因为我认为它不能是静态的而是变化的?

回答by mucio

Function MySheet()

  ' uncomment the below line to make it Volatile
  'Application.Volatile
   MySheet = Application.Caller.Worksheet.Name

End Function

This should be the function you are looking for

这应该是您正在寻找的功能

回答by moberme

This works for me.

这对我有用。

worksheetName = ActiveSheet.Name  

回答by josef

Sub FnGetSheetsName()

    Dim mainworkBook As Workbook

    Set mainworkBook = ActiveWorkbook

    For i = 1 To mainworkBook.Sheets.Count

    'Either we can put all names in an array , here we are printing all the names in Sheet 2

    mainworkBook.Sheets("Sheet2").Range("A" & i) = mainworkBook.Sheets(i).Name

    Next i

End Sub

回答by Rohit Pal

You can use below code to get the Active Sheet name and change it to yours preferred name.

您可以使用以下代码获取活动工作表名称并将其更改为您的首选名称。

Sub ChangeSheetName()

Dim shName As String
Dim currentName As String
currentName = ActiveSheet.Name
shName = InputBox("What name you want to give for your sheet")
ThisWorkbook.Sheets(currentName).Name = shName

End Sub

回答by ChaCha CJ Rune

Extend Code for Show Selected Sheet(s) [ one or more sheets].

扩展用于显示选定工作表的代码 [一张或多张纸]。

Sub Show_SelectSheet()
  For Each xSheet In ThisWorkbook.Worksheets
     For Each xSelectSheet In ActiveWindow.SelectedSheets
         If xSheet.Name = xSelectSheet.Name Then
            '=== Show Selected Sheet ===
            GoTo xNext_SelectSheet
         End If
     Next xSelectSheet
  xSheet.Visible = False  
xNext_SelectSheet:
Next xSheet
MsgBox "Show Selected Sheet(s) Completed !!!"
end sub