UserForm将文本更改为大写,小写或使用适当的函数

时间:2016-05-06 20:14:57

标签: vba excel-vba excel

人!

此时我创建了一个UserForm,使用三个选项更改文本中的字母:

  1. 大写
  2. 小写
  3. 正确的功能
  4. 我的第一个代码使用了If-Then结构,没问题。我把它放在下面:

    Private Sub OkButton_Click()
        Dim WorkRange As Range
        Dim cell As Range
    
    'Detects only constant type (text; excludes formulas)
        On Error Resume Next
        Set WorkRange = Selection.SpecialCells(xlCellTypeConstants, xlCellTypeConstants)
    
    'Uppercase
        If OptionUpper Then
            For Each cell In WorkRange
                cell.Value = UCase(cell.Value)
        Next cell
        End If
    
    'Uppercase
        If OptionLower Then
            For Each cell In WorkRange
                cell.Value = LCase(cell.Value)
            Next cell
        End If
    
    'Using Proper Function
        If OptionProper Then
            For Each cell In WorkRange
                cell.Value = Application.WorksheetFunction.Proper(cell.Value)
            Next cell
        End If
        Unload UserForm1
    End Sub
    
    
    Private Sub UserForm_Click()
    
    End Sub
    

    我使用了一种模式来运行UserForm1:

    Sub ChangeCase2()
        If TypeName(Selection) = "Range" Then
            UserForm1.Show
        Else
            MsgBox "Selection a range.", vbCritical
        End If
    End Sub
    

    一切正常。但后来我想:是否有可能使用Select Case结构?所以我试过,不幸的是,没有跑。大写选项用作小写,而小写和Proper用作大写。我查看了我给按钮的字幕,一切都很好。请帮助我吗?

    Private Sub CancelButton_Click()
        Unload UserForm2 
    End Sub
    
    Private Sub OkButton_Click()
        Dim WorkRange As Range
        Dim cell As Range
        Dim OptionSelect As Variant
    
        On Error Resume Next
        Set WorkRange = Selection.SpecialCells(xlCellTypeConstants, xlCellTypeConstants)
    
        Select Case OptionSelect
            Case OptionUpper 'Letras Maiúsculas
                For Each cell In WorkRange
                    cell.Value = UCase(cell.Value)
                Next cell
            Case OptionLower 'Letras Minúsculas
                For Each cell In WorkRange
                    cell.Value = LCase(cell.Value)
                Next cell
            Case OptionProper 'Iniciais Maiúsculas
                For Each cell In WorkRange
                    cell.Value = Application.WorksheetFunction.Proper(cell.Value)
                Next cell
        End Select
        Unload UserForm2
    End Sub
    

    我使用了UserForm2的另一种模式:

    Sub ChangeCase3()
        If TypeName(Selection) = "Range" Then
            UserForm2.Show
        Else
            MsgBox "Selection a range.", vbCritical
        End If
    End Sub
    

2 个答案:

答案 0 :(得分:0)

第一个代码从某处获取OptionSelect的值。

如果它在那里工作,那么问题是在你的第二个代码中你有这个额外的行:

Dim OptionSelect As Variant

在这一行上你将这个值设为空,所以它会使Select Case没用,因为没有值。

答案 1 :(得分:0)

而不是

Select Case OptionSelect

使用

Select Case True

这将为您提供匹配OptionButtons值与

的正确值