将字符串转换为大写的函数

7

我一直在尝试编写一个用户定义函数,使其返回大写字母的值,使用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 就能工作,但是无法将输入的字符串全部转为大写。

1
对于VBA(而非VB.Net),只需使用sInput = UCase(sInput) - Dmitry Pavliv
1
这解释了很多问题。至少我不是疯了。再次感谢simoco。 - user2993456
2个回答

16

只是错误的函数。你想要的是

sInput = UCase(sInput)
希望这有所帮助。

问题的答案已经被接受,并且问题的标题已更改。希望这能让未来的用户更容易找到它。 - user2993456

0

确认函数 UCase(...) 正常工作。这里是另一个例子:“将第二行第二列到末尾的首字母大写”:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接