修改/更改单元格Excel VBA的第N个元素

我正在创build一个macros观扭转单元值的大写,来解释更好。

原始值 –

hh3crd220 xmi4Idc200 TEst02NoW 

输出 –

 HH3CRD220 XMI4iDC200 teST02nOw 

我认为必须已经有macros可以做这项工作,但我自己编写一个,一切正常工作,除了改变第n个值, 中期不工作,因为它只会提取的价值,我试图字符,但只会格式化元素,我想像character.value或mid.value函数的工作。

 Sub CapsChange() Dim letr As String Dim Val1 As String Dim sr As Range lastrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row Set sr = Range("A1:A" & lastrow) For Each r In sr Fval = r.Value Val1 = Left(r.Value, 1) If Val1 <> UCase(Val1) Then For i = 1 To Len(Fval) letr = Mid(Fval, i, 1) If letr = UCase(letr) Then **'First Code try** letr = LCase(letr) **'Second Code try** r.Characters(i, 1).Value = LCase(letr) Else letr = UCase(letr) r.Characters(i, 1).Value = UCase(letr) End If Next i End If Next End Sub 

只需要帮助改变/控制单元格值的第n个字符,就像我们使用单元格(x,y).value = XXX。

尝试这个:

使用SUB()的变体1

 Sub Test() Dim rng As Range, cl As Range, i& Set rng = Range("A1:A" & Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row) For Each cl In rng.Cells For i = Len(cl.Value) To 1 Step -1 With cl.Characters(i, 1) If .Text = UCase(.Text) Then .Text = LCase(.Text) ElseIf .Text = LCase(.Text) Then .Text = UCase(.Text) End If End With Next i, cl End Sub 

变体2使用Function()

 Public Function ReverseCase(cl As Range) Dim StringOutput$, i& For i = Len(cl.Value) To 1 Step -1 With cl.Characters(i, 1) If .Text = UCase(.Text) Then StringOutput = LCase(.Text) & StringOutput ElseIf .Text = LCase(.Text) Then StringOutput = UCase(.Text) & StringOutput End If End With Next i ReverseCase = StringOutput End Function 

testing函数()

在这里输入图像描述

两个变种都经过testing,工作正常

您可以使用Mid 语句 ,它允许修改string:

 Sub CapsChange() Dim letr As String Dim Val1 As String Dim sr As Range lastrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row Set sr = Range("A1:A" & lastrow) For Each r In sr Fval = r.Value Val1 = Left(r.Value, 1) If Val1 <> UCase(Val1) Then For i = 1 To Len(Fval) letr = Mid(Fval, i, 1) If letr = UCase(letr) Then Mid(Fval,i,1) = LCase(letr) else Mid(Fval,i,1) = UCase(letr) End If Next i End If Next End Sub 

像下面的function将更容易重用!

以下是如何使用它:

 Option Explicit Sub test_Angad_Arora() Dim wS As Worksheet, _ LastRow As Long, _ i As Long Set wS = ActiveSheet With wS LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row For i = 1 To LastRow .Cells(i, 1) = InvertCaseCore(.Cells(i, 1)) Next i End With End Sub 

而反转inputstring容量的函数:

 Public Function InvertCaseCore(StringToReCapitalize As String) Dim l As Integer, _ c As String, _ OutPut As String, _ i As Integer l = Len(StringToReCapitalize) For i = 1 To l c = Mid(StringToReCapitalize, i, 1) If (c >= "A") And (c <= "Z") Then c = LCase(c) ElseIf (c >= "a") And (c <= "z") Then c = UCase(c) End If OutPut = OutPut & c Next i InvertCaseCore = OutPut End Function 

您正在寻找replacefunction( 请参阅此链接 )。 一个例子:

 Replace("abCabCde", "C", "c", , 1) 

这将在“abCabCde”中find第一个(也是唯一的第一个)“C”,并用“c”replace为“abcabCde”。