我有一个名为Search
的代码,用于查找搜索项的单元格引用。之后我想使用以下方法获取搜索值的范围:
Search.Address
一旦vba获得了地址,请说$A$1
,我想将$A
更改为$M
,因此返回值为$M$1
这可能吗?
谢谢!
答案 0 :(得分:3)
这是一个班轮?
Debug.Print Range("M" & Range(rangeAddress).Row).Address
rangeAddress
存储$A$1
或其他任何地址。
答案 1 :(得分:2)
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()
子并查看立即窗口 CTRL + G
或将其用作此类电子表格函数
=SwapColumns(A1, "M")
将代码添加到模块
注意: Sub被称为SwapColumn
,函数SwapColumns
最后有s
。
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
答案 2 :(得分:1)
好的,我必须遗漏一些东西,为什么不简单地使用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