函数将String转换为大写

时间:2014-03-07 19:12:29

标签: vba excel-vba excel-udf excel

我一直在尝试创建一个用户定义的函数,我在VBA中使用String.ToUpper()方法以全部大写形式返回它的值。当我尝试在excel中使用我的UDF时,我得到一个编译器错误,只是突出显示了我的UDF的顶行:

Function removeSpecial(sInput As String) As String

以下是完整的代码:

Function removeSpecial(sInput As String) As String
    Dim sSpecialChars As String
    Dim i As Long
    sSpecialChars = "\/:*?™""®<>|.&@# (_+`©~);-+=^$!,'" 'This is your list of characters to be removed
    For i = 1 To Len(sSpecialChars)
        sInput = Replace$(sInput, Mid$(sSpecialChars, i, 1), "")

    Next
    sInput = sInput.ToUpper()
    removeSpecial = sInput
End Function

代码可以正常删除特殊字符,但我希望它也将输入的字符串转换为大写字母。

我尝试添加时开始收到此错误:

sInput = sInput.ToUpper()

如果此代码被注释掉,我的UDF可以工作,但不会在所有Upper中返回输入的字符串。

2 个答案:

答案 0 :(得分:14)

错误的功能。你想要

sInput = UCase(sInput)

希望有所帮助

答案 1 :(得分:0)

确认UCase(...)功能正常。这是另一个例子“将第2列中的第一个字母从第2行大写到结尾”:

Sub UpCaseMacro()

' Declare variables
Dim OldValue As String
Dim NewValue As String
Dim FirstLetter As String
Dim i As Long

' Select values
lastRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row
ActiveSheet.Range(Cells(2, 2), Cells(lastRow, 2)).Select

' Update data
For i = 2 To Selection.Rows.Count
    If Not IsEmpty(Cells(i, 2).Value) Then
        OldValue = Cells(i, 2).Value
        FirstLetter = Left(Cells(i, 2).Value, 1)
        NewValue = UCase(FirstLetter) & Right(OldValue, Len(OldValue) - 1)
        Cells(i, 2).Value = NewValue
    End If
  Next i
 End Sub
相关问题