1

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

Search.Address

一旦 vba 获得地址,比如说$A$1,我想更改$A$M所以返回值将是$M$1

这可能吗?

谢谢!

4

3 回答 3

3

这是一个班轮?

Debug.Print Range("M" & Range(rangeAddress).Row).Address

商店rangeAddress$A$1任何其他地址。

于 2013-10-10T12:55:12.123 回答
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()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

在此处输入图像描述

于 2013-10-10T11:00:18.490 回答
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
于 2013-10-10T11:44:57.253 回答