2015-05-27 59 views
0

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

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") 

回答

0

你可以这样做:

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 
+0

这篇对你的工作? – Gustav

相关问题