excel - 使用VBA替换字符串中特定位置的文本
问题描述
我想通过指定 substring_a 的位置和长度,用字符串中的另一个子字符串 (substring_b) 替换一个子字符串 (substring_a)。
我正在尝试使用 Mid 函数,但它似乎不起作用,除非 substring_b 等于或长于 substring_a
这是我的代码:
Sub Test_Mid()
Dim starting_text As String
Dim replacement_text As String
starting_text = "Long Starting Text"
replacement_text = "End"
Mid(starting_text, 6, 8) = replacement_text
MsgBox (starting_text)
End Sub
我希望代码返回“Long End Text”,但它返回“Long Endrting Text”。
我该如何解决?
注:以上为说明性示例。我不能直接将 Replace 函数与 replacement_text 一起使用,因为在我的实际宏中,replacement_text 是可变的。
解决方案
You are making a simple thing overly complex. All that is needed is a simple replace.
starting_text = Replace(starting_text, "Starting", "End")
To replace just the 1st occurrence, use this:
starting_text = Replace(starting_text, "Starting", "End", 1, 1)
Or if it's just one occurrence, starting at a specific location, use this:
starting_text = Replace(starting_text, "Starting", "End", Instr(starting_text, "Starting"), 1)
Or if it's just one occurrence, starting at a specific location, and you dont want it to be case sensitive, use this:
starting_text = Replace(starting_text, "Starting", "End", Instr(starting_text, "Starting", vbTextCompare), 1, vbTextCompare)
推荐阅读
- javascript - 如何使用 USB 指纹扫描设备验证我的电子应用程序?
- python - 如何比较python字典中键值对之间的值?
- javascript - 声明变量时使用 var 和 not 有什么区别?
- python - Python创建一个从url中提取图片然后调整为缩略图的函数
- android - 如何从发送好友请求的firebase数据库中获取所有用户
- java - 坚持从控制台检测下一行
- java - 当类名在同一个类中使用两次时,java传递一个变量
- actions-on-google - 如何在 Google 上为基本卡片添加边框
- ruby-on-rails - 如何验证参数值(字符串)?
- c# - ASP.NET MVC - 如何找到返回响应的代码