在VBA中替换字符串中字符的最快方法
问题描述:
我有一个字符串(一个excel范围),例如“$ A $ 1:$ AB $ 1200”。在VBA中替换字符串中字符的最快方法
我需要更换起始范围的行(在这里,1)一些其他的价值,比如,6(因此字符串变成 “$ A $ 6:$ AB $ 1200”)
我用下面的代码试过,但它似乎变得太复杂了
Dim stRng As String
stRng = Split(usdRange, ":")(0)
Dim row2bRepl As Long
row2bRepl = Right(stRng, Len(stRng) - InStr(2, stRng, "$"))
usdRange = Replace(stRng, row2bRepl, hdrRow, InStr(2, stRng, "$"))
有关如何实现这个更简单的任何帮助?
TIA!
答
这是非常快速,非常直接!
Sub test()
Dim s1 As String, s2 As String
s1 = "$A$1:$AB$1200"
s2 = Intersect(Range(s1), Range(s1).Offset(5, 0)).Address 'evaluates to $A$6:$AB$1200
End Sub
根据您的意见,在这里你可以看到它工作得很好用完全随机的范围内,只有在运行时确定
Sub test()
Dim usdRange As String, usdRange2 As String
Dim lastRow As Long, lastCol As Long
lastRow = Application.WorksheetFunction.RandBetween(10, 100)
lastCol = Application.WorksheetFunction.RandBetween(1, 100)
usdRange = Range("A1", Cells(lastRow, lastCol)).Address
usdRange2 = Intersect(Range(usdRange), Range(usdRange).Offset(5, 0)).Address
Debug.Print usdRange, usdRange2
End Sub
输出以下,按指定量抵消所有范围:
Old string New string
$A$1:$CF$22 $A$6:$CF$22
$A$1:$AA$93 $A$6:$AA$93
$A$1:$N$82 $A$6:$N$82
答
这样的事情会起作用。它不是简单多了,但它看起来很简单:
Public Sub ReplaceString()
Dim strInput As String
Dim lngFrom As Long
Dim lngTo As Long
strInput = "$A$1:$AB$1200"
lngFrom = InStr(2, strInput, "$")
lngTo = InStr(1, strInput, ":")
Debug.Print Left(strInput, lngFrom) & "77" & Right(strInput, Len(strInput) - lngFrom-1)
End Sub
它采用左侧和字符串的右侧位置,并在中间放新的价值,在这种情况下77
。
+0
谢谢@Vityata,这工作:)但只是想知道这是否仍然可以简化... – NetTechie
最快的方法还是更方便的方法? – Tehscript
更快选择! – NetTechie