我有一个名为Search
查找搜索项的单元格引用的代码。之后,我想使用以下方法获取搜索值的范围:
Search.Address
一旦 vba 获得地址,比如说$A$1
,我想更改$A
为$M
所以返回值将是$M$1
这可能吗?
谢谢!
这是一个班轮?
Debug.Print Range("M" & Range(rangeAddress).Row).Address
商店rangeAddress
或$A$1
任何其他地址。
Sub Main()
Dim rangeAddress As String
rangeAddress = Range("A1").Address
Debug.Print "Before conversion: " & rangeAddress
SwapColumn rangeAddress, "M"
Debug.Print "After conversion: " & rangeAddress
End Sub
Private Sub SwapColumn(ByRef r As String, ByVal newCol As String)
Dim arr As Variant
arr = Split(r, "$")
r = vbNullString
Dim i As Long
For i = LBound(arr) To UBound(arr)
If i = 1 Then
r = "$" & r & newCol & "$"
Else
r = r & arr(i)
End If
Next i
End Sub
运行Main()
sub 并查看即时窗口CTRL+G
或将其用作这样的电子表格功能
=SwapColumns(A1, "M")
将代码添加到模块
注意: Sub 被调用SwapColumn
并且函数SwapColumns
以 as
结尾。
Function SwapColumnS(r As Range, newCol As String) As String
Dim rngAddress As String
rngAddress = r.Address
Dim arr As Variant
arr = Split(rngAddress, "$")
rngAddress = vbNullString
Dim i As Long
For i = LBound(arr) To UBound(arr)
If i = 1 Then
rngAddress = "$" & rngAddress & newCol & "$"
Else
rngAddress = rngAddress & arr(i)
End If
Next i
SwapColumnS = rngAddress
End Function
好的,我一定遗漏了一些东西,为什么不简单地使用 REPLACE:
Sub Main()
Dim rangeAddress As String
rangeAddress = Range("A1").Address
Debug.Print "Before conversion: " & rangeAddress
rangeAddress = Replace(rangeAddress, "$A$", "$M$")
Debug.Print "After conversion: " & rangeAddress
End Sub