【问题标题】:Error to replace letters to other将字母替换为其他错误
【发布时间】:2016-02-03 17:04:50
【问题描述】:

为什么这段代码不能正常工作?任务是仅在第一次发生时从正确的位置替换(str.和strasse)。在测试中它什么都不做。

我猜错误在这一行:x.Value = StrReverse(Replace(StrReverse(x.Value), strArr(b), "straße", 1, 1)) 错误在哪里。

Sub strreplace()
Dim strArr As Variant
Dim b As Byte
Dim x As Range

strArr = Array("str.", "strasse", """")

For Each x In Selection.Cells
For b = 0 To UBound(strArr)
x.Value = StrReverse(Replace(StrReverse(x.Value), strArr(b), "straße", 1, 1))
Next b
Next x
End Sub

我测试的第二个代码是:

Sub strReplace()
Dim strArr As Variant
Dim b As Byte

strArr = Array("str.", "strasse", """")

For Each x In Selection
For b = 0 To UBound(strArr)
If InStrRev(x, strArr(b)) > 0 Then
Selection.Replace x, Replace(x, strArr(b), "straße", InStrRev(x,  strArr(b)))
End If
Next b
Next
End Sub

This code transform example:

"Lessonstrasse" in straße without Lesson...

【问题讨论】:

  • 只有在第一次出现时才从正确的位置 -> 你的意思是.str.strasse最右边 的话在单元格值中?
  • 请显示您的预期输出
  • 另外,在您的第一个宏中,您在xREVERSED 字符串中搜索strArr(b)。你永远找不到它,除非你搜索strArr(b)的反面。

标签: string excel vba replace


【解决方案1】:

既然你已经反转了你正在搜索的字符串,那么你正在寻找的字符串也需要反转。所以"strArr(b)" 应该变成StrReverse(strArr(b))。下面的代码更正了这一点,并更改了要演示的数组文本。

另外,我注意到您的替换文本没有点。您可能想要使用".straße" 而不是"straße"。此外,您可能会发现用户定义的函数对此更方便,但当然,我不知道您是使用上下文。

Sub strreplace()
    Application.ScreenUpdating = False
    Dim strArr As Variant
    Dim b As Byte
    Dim x As Range

    strArr = Array(".Ext1", ".Ext2")

    For Each x In Selection.Cells
        For b = 0 To UBound(strArr)
            x.Value2 = StrReverse(Replace(StrReverse(x.Value2), StrReverse(strArr(b)), "straße", 1, 1))
        Next b
    Next x
End Sub

结果...

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2021-11-02
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多