在VBA中更改Excel工作表名称

时间:2015-05-27 09:09:06

标签: ms-access access-vba ms-access-2010

我需要使用文本框数据更改工作表“USS IWO JIMA”,换句话说,工作表的名称应来自文本框。我试过但不能这样做

Set objApp = New Excel.Application
'This is new 'Your excel spreadsheet      file goes here
Set objBook = objApp.Workbooks.Add(strTemplatePath)
'Name of sheet you want to export to
Set objApp = objBook.Parent
Set objSheet = objBook.Worksheets("USS IWO JIMA")

1 个答案:

答案 0 :(得分:1)

你可以这样做:

Public Sub RenameWorkSheet()

    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet

    Set xls = New Excel.Application
    Set wkb = xls.Workbooks.Open("c:\test\workbook1.xlsx")
    Set wks = wkb.Worksheets(1)

    wks.Name = "My New Name"
    wkb.Close True

    Set wks = Nothing
    Set wkb = Nothing

    xls.Quit

    Set xls = Nothing

End Sub

请注意,不允许任何名称:

Public Function TrimExcelSheetName( _
  ByVal strSheetName As String) _
  As String

' Replaces characters in strSheetName that are
' not allowed by Excel in a sheet name.
' Truncates length of strSheetName to clngSheetNameLen.
'
' 2000-12-07. Gustav Brock, Cactus Data ApS, Copenhagen
' 2002-05-22. Extended selection of invalid chars.
'             Replaced string concatenating with Mid().

  ' No special error handling.
  On Error Resume Next

  ' ' String containing all not allowed characters, minimum.
  ' Const cstrInValidChars  As String = "\/:*?"
  ' String containing all not allowed characters, extended.
  Const cstrInValidChars  As String = "\/:*?""<>|[]"
  ' Replace character for not allowed characters.
  Const cstrReplaceChar   As String * 1 = "-"
  ' Maximum length of a sheet name in Excel.
  Const clngSheetNameLen  As Long = 31

  Dim lngLen    As Long
  Dim lngPos    As Long
  Dim strChar   As String
  Dim strTrim   As String

  ' Strip leading and trailing spaces.
  strTrim = Left(Trim(strSheetName), clngSheetNameLen)
  lngLen = Len(strTrim)
  For lngPos = 1 To lngLen Step 1
    strChar = Mid(strTrim, lngPos, 1)
    If InStr(cstrInValidChars, strChar) > 0 Then
      Mid(strTrim, lngPos) = cstrReplaceChar
    End If
  Next

  TrimExcelSheetName = strTrim

End Function