Geo*_*rge 8 excel vba excel-vba
在JAVA或C++中,我们可以做一些事情myString.insert(position, word).有没有办法在Excel VBA的字符串中执行相同的操作?在我的工作表中,我有一个字符串看起来像这样:01 / 01 / 995,我想在年份中插入1,所以制作它01 / 01 / 1995.
Dim test_date As String
test_date = "01 / 25 / 995"
test_date = Mid(test_date, 1, 10) & "1" & Mid(test_date, 11, 4)
Run Code Online (Sandbox Code Playgroud)
还有另一种更简单/更优雅的方式吗?
T I*_*T I 13
我不认为有一种更简洁的方法,所以你可以把它包装在一个函数中.另一种方法是replace,但它不是更清洁.
Function Insert(source As String, str As String, i As Integer) As String
Insert = Replace(source, tmp, str & Right(source, Len(source)-i))
End Function
Run Code Online (Sandbox Code Playgroud)
或者只是修改你拥有的东西
Function Insert(source As String, str As String, i As Integer) As String
Insert = Mid(source, 1, i) & str & Mid(source, i+1, Len(source)-i)
End Function
Run Code Online (Sandbox Code Playgroud)
这是已接受答案的版本,添加了测试并按照我期望的方式工作:
Function Insert(original As String, added As String, pos As Long) As String
If pos < 1 Then pos = 1
If Len(original) < pos Then pos = Len(original) + 1
Insert = Mid(original, 1, pos - 1) _
& added _
& Mid(original, pos, Len(original) - pos + 1)
End Function
Run Code Online (Sandbox Code Playgroud)
测试通过:
Public Sub TestMe()
Debug.Print Insert("abcd", "ff", 0) = "ffabcd"
Debug.Print Insert("abcd", "ff", 1) = "ffabcd"
Debug.Print Insert("abcd", "ff", 2) = "affbcd"
Debug.Print Insert("abcd", "ff", 3) = "abffcd"
Debug.Print Insert("abcd", "ff", 4) = "abcffd"
Debug.Print Insert("abcd", "ff", 100) = "abcdff"
End Sub
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31390 次 |
| 最近记录: |