gpt4 book ai didi

vba - 在VBA中替换字符串中字符的最快方法

转载 作者:行者123 更新时间:2023-12-04 21:33:01 25 4
gpt4 key购买 nike

我有一个字符串(一个 excel 范围),例如“$A$1:$AB$1200”。

我需要将起始范围的行(此处为 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, "$"))

关于如何更简单地实现这一点的任何帮助?

蒂亚!

最佳答案

这是非常快速且非常直接的!

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

关于vba - 在VBA中替换字符串中字符的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46565614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com