如何更改地址属性的“列”部分

时间:2013-10-10 10:51:02

标签: excel excel-vba vba

我有一个名为Search的代码,用于查找搜索项的单元格引用。之后我想使用以下方法获取搜索值的范围:

Search.Address

一旦vba获得了地址,请说$A$1,我想将$A更改为$M,因此返回值为$M$1

这可能吗?

谢谢!

3 个答案:

答案 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

enter image description here


或将其用作此类电子表格函数

=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

enter image description here

答案 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