使用Excel VBA获取工作表名称

时间:2013-10-11 16:47:57

标签: excel excel-vba vba

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

我可以用
sheetname = ActiveSheet.Name

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

无论如何都要解决这个问题 - 或者可能因为我认为它不是静态的而是变化的?

6 个答案:

答案 0 :(得分:29)

Function MySheet()

   MySheet = Application.Caller.Worksheet.Name

End Function

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

答案 1 :(得分:5)

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

答案 2 :(得分:3)

这适合我。

worksheetName = ActiveSheet.Name  

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

扩展代码以显示所选的工作表[一张或多张工作表]。

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

答案 5 :(得分:-3)

我需要通过打开文件的名称更改工作表名称

Sub Get_Data_From_File5()
    Dim FileToOpen As Variant
    Dim OpenBook As Workbook
    Dim currentName As String
    currentName = ActiveSheet.Name
    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.csv*),*csv*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(1).Range("A1:g5000").Copy
        ThisWorkbook.Worksheets(currentName).Range("Aw1:bc5000").PasteSpecial xlPasteValues
        OpenBook.Close False
       
        
    End If
    Application.ScreenUpdating = True
End Sub