【问题标题】:VBA: Convert range to cell numbers e.g. (1,1)VBA:将范围转换为单元格编号,例如(1,1)
【发布时间】:2018-06-20 14:33:13
【问题描述】:

通过使用此代码,我在工作表中选择了一个范围。 例如。 “BE5:BE182”作为此代码的返回:

MsgBox "Selected range: " & Selection.Areas(1).Address(False, False)

现在我想要我的 retrive BE5 并将其转换为两个 col 的数值。和行(例如 1,1),我也想为 BE182 执行此操作。我该怎么做?

野心:我对宏的目标是选择一个应该附加数字数据的范围。根据范围开始和范围结束之间的行数,我将始终使用存储国家名称的 col 1 (A)。针对这些,我想针对来自另一个工作簿的数据实现类似的 VLOOKUP 功能 - 用户还应该选择应该从中获取数据的范围。

让用户定义 col 的想法。并且 row-range 是针对 vlook-up 的 row-range 可以更改,并且 col 可能并不总是只是 +1。

提前非常感谢!

【问题讨论】:

  • 你已经知道1,1 所以没有理由写代码给你。本质上Selection.Cells(1,1) 指的是BE5。要获得范围的大小,您可以使用Selection.Rows.CountSelection.Columns.Count。这意味着:Selection.Cells(1,1).Offset(Selection.Rows.Count, Selection.Columns.Count) 将为您提供范围/单元格BE182。我不知道你想做什么,因为你的问题不是很清楚。
  • 那么 Selection.Cells(1,1) 是 BE5 吗?我不明白 ^^ - 谢谢。但是我如何将其“分解”为数值 x(例如 48) - 代表 BE,y (5) 代表 5?可以这么说,我需要 A1 中的 BE5 的数值,并且分别在 x 和 y 中。

标签: excel vba


【解决方案1】:

您可以使用范围的RowColumn 属性来获取范围的数值范围。

Dim Selected As String
Dim SelectedRange() As String
Dim BeginSel As String
Dim EndSel As String

' Get the range of cells selected by the user.
Selected = Selection.Areas(1).Address(False, False)
MsgBox "Selected range: " & Selected

' Split the selected range into begin and end cells.
SelectedRange = Split(Selected, ":")
BeginSel = SelectedRange(0)
EndSel = SelectedRange(1)

MsgBox "Begin Selected range: " & BeginSel
MsgBox "End Selected range: " & EndSel

' Convert the begin and end cells to row and column values
MsgBox Range(BeginSel).Row & ", " & Range(BeginSel).Column
MsgBox Range(EndSel).Row & ", " & Range(EndSel).Column

在这里,我在":" 字符上拆分所选范围以获取范围的开始和结束单元格。您可能需要检查Split 函数返回的数组的长度,以确保用户选择了实际的范围 单元格而不是单个单元格(或什么都没有)。

这会将选定范围 A1:E3 转换为坐标 (1, 1) 和 (3, 5),例如。

【讨论】:

    【解决方案2】:

    怎么样:

    Sub RowAndColumn()
        Dim r1 As Range, r2 As Range, addy As String
    
        addy = Selection.Address(0, 0)
        If Selection.Count = 1 Then
            MsgBox Selection.Row & "," & Selection.Column
        Else
            arr = Split(addy, ":")
            Set r1 = Range(arr(0))
            Set r2 = Range(arr(1))
            MsgBox r1.Row & "," & r1.Column & vbCrLf & r2.Row & "," & r2.Column
        End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2016-02-29
      • 1970-01-01
      • 2012-12-06
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      相关资源
      最近更新 更多