使用vba删除最后4个字符,并replace同一单元格中的新单词/数字

我认为这个问题可能有一个非常简单的解决scheme,但是我很难find它,而且现在我只使用/学习VBA了几天。

我试图使用VBA删除一个空间和美元数字后的字母美元。 这发生在我的工作表中只有3个特定的单元格中,并发生在我的工作簿中的所有后续工作表上。 现在我不担心循环其他工作表。

下面是我发现的代码,如果我手动select我想要的代码工作的单元格,但我想将它绑定到一个button,这样的过程发生,而不必我select单元格。

Sub RemoveUSD() Dim Cell As Range, Str As String, StrLen1 As Integer, StrLen2 As Integer ' For each cell in your current selection For Each Cell In selection ' Set StrLen1 as the length of the current cell value StrLen1 = Len(Cell.Value) ' Set StrLen2 as the original length minus 3 StrLen2 = StrLen1 - 3 ' Set Str as the original cell value minus the last 3 characters Str = Left(Cell.Value, StrLen2) ' Update the adjacent cell with the shortened value Cell.Value = Str ' Check next cell in selection Next Cell End Sub 

只需input工作簿名称,工作表名称和范围,这将为你做。 我把Trim放在任何领先或尾随的空白处。 要将其附加到button上,请添加一个button(“开发工具”选项卡>“控件”>“插入”),然后select要附加的macros。

 Sub RemoveUSD() Dim Cell As Range, rng as Range Dim Str As String Dim StrLen1 As Integer, StrLen2 As Integer With Workbooks("Daily MSR VaR Automation Attempt") With .Sheets("8-30 copy") Set rng = .Range("E2,N2,W2") End With End With ' For each cell in your current selection For Each Cell In rng ' Set StrLen1 as the length of the current cell value StrLen1 = Len(Cell.Value) ' Set StrLen2 as the original length minus 3 StrLen2 = StrLen1 - 3 ' Set Str as the original cell value minus the last 3 characters Str = Trim(Left(Cell.Value, StrLen2)) ' Update the adjacent cell with the shortened value Cell.Value = Str ' Check next cell in selection Next Cell End Sub 

你可以直接在一个范围内加上检查是否

  • 单元格至less有四个字符,
  • 最后四个字符是“美元”

对于A1:A30

 [a1:A30] = Application.Evaluate("=IF(LEN(A1:A30)>4,IF(RIGHT(A1:A30,4)="" USD"",LEFT(A1:A30,LEN(A1:A30)-4),A1:A30),A1:A30)")