I have a string (an excel range) something like "$A$1:$AB$1200".
I need to replace the row of starting range (here, 1) to some other value, say, 6 (so string becomes "$A$6:$AB$1200")
I tried with below code, but it seems to getting too complicated
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, "$"))
Any help on how to achieve this simpler?
TIA!
This is pretty quick and very straight forward!
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
As per your comments, here you can see it works perfectly well with a completely random range, only determined at runtime
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
Outputs the following, offsetting all ranges by the specified amount:
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
Something like this will work. It is not a lot simpler, but it looks simple:
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
It takes the left and the right positions of the string and puts in the middle the new value, in this case 77
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.