userform文本框以显示活动工作表名称

时间:2017-04-06 05:27:32

标签: excel excel-vba vba

在我的工作簿中有50个工作表,我创建了一个用户窗体,弹出一个文本框,可以帮助我更改工作表名称,当我切换不同的工作表时,我希望当前工作表名称应该显示在该文本框中然后我将使用下面的代码修改工作表名称。

您能否告诉我一个代码行,文本框显示当前工作表名称。

请在下面的代码中找到我可以通过在文本框中输入名称来更改现有工作表名称的帮助Sheetnametext

Private Sub Sheetnametext_Change()

'If the length of the entry is greater than 31 characters, disallow the entry.

If Len(Sheetnametext) > 31 Then
    MsgBox "Worksheet tab names cannot be greater than 31 characters in length." & vbCrLf & "You entered " & mysheetname & ", which has " & Len(mysheetname) & " characters.", , "Keep it under 31 characters"
    Exit Sub
End If

'Sheet tab names cannot contain the characters /, \, [, ], *, ?, or :. 'Verify that none of these characters are present in the cell's entry.
Dim IllegalCharacter(1 To 7) As String, i As Integer

IllegalCharacter(1) = "/"
IllegalCharacter(2) = "\"
IllegalCharacter(3) = "["
IllegalCharacter(4) = "]"
IllegalCharacter(5) = "*"
IllegalCharacter(6) = "?"
IllegalCharacter(7) = ":"

For i = 1 To 7
    If InStr(Sheetnametext, (IllegalCharacter(i))) > 0 Then
        MsgBox "You used a character that violates sheet naming rules." & vbCrLf & vbCrLf & "Please re-enter a sheet name without the ''" & IllegalCharacter(i) & "'' character.", 48, "Not a possible sheet name !!"
        Exit Sub
    End If
Next i

'Verify that the proposed sheet name does not already exist in the workbook.
Dim strSheetName As String, wks As Worksheet, bln As Boolean

strSheetName = Trim(Sheetnametext)

On Error Resume Next
Set wks = ActiveWorkbook.Worksheets(strSheetName)
On Error Resume Next

If Not wks Is Nothing Then
    bln = True
Else
    bln = False
    Err.Clear
End If

'History is a reserved word, so a sheet cannot be named History.
If UCase(mysheetname) = "HISTORY" Then
    MsgBox "A sheet cannot be named History, which is a reserved word.", 48, "Not allowed"
    Exit Sub
End If

'If the worksheet name does not already exist, name the active sheet as the InputBox entry.
'Otherwise, advise the user that duplicate sheet names are not allowed.
If bln = False Then
    ActiveSheet.Name = strSheetName
End If

End Sub

1 个答案:

答案 0 :(得分:0)

最好使用列表框导航工作簿中的表单,尝试此代码。

Private Sub UserForm_Initialize()

Dim N As Long 对于N = 1到ActiveWorkbook.Sheets.Count ListBox1.AddItem ActiveWorkbook.Sheets(N).Name 下一个N

End Sub