Excel VBA将单元格名称转换为其坐标

5

假设我有一个字符串代表一个单元格:A2
要将其转换为坐标:(2, 1),应该怎么做?

2个回答

4

没有VBA

假设单元格C2包含字符串"A2"

那么

  • =INDIRECT(C2)返回引用A2
  • =ROW(INDIRECT(C2))返回行号-2
  • =COLUMN(INDIRECT(C2))返回列号-1
  • ="(" & ROW(INDIRECT(C2)) & "; " & COLUMN(INDIRECT(C2)) & ")"以格式(x; y)-(2; 1)返回坐标

enter image description here

更新:

如果您使用UDF,请将参数类型从String更改为Range

Function GetData(Cell As Range)
    MsgBox "My row is " & Cell.Row
    MsgBox "My column is " & Cell.Column
End Function

如果你在工作表中这样调用UDF: =GetData(A2),将会弹出消息框:

  • "我的行数是2"
  • "我的列数是1"

在这种情况下,=offset(ref,rows,cols,width,height) 也可能非常有用。 - Hannu
@AnDrOiD,我注意到你正在使用函数Function GetData(Cell As String)...。你是想像用户定义的函数一样使用它(在单元格中=GetData(A2)),并且想要定义A2的坐标吗? - Dmitry Pavliv
1
@simoco 非常感谢您! - Eyal

2
您可以使用 Range 对象的 Column 和 Row 属性:
Range("A2").Row
Range("A2").Column

例子:

Sub test()
  Dim x As String
  x = "A2"
  MsgBox GetRow(x) & " " & GetColumn(x)
End Sub

 Function GetRow(Cell As String)
    GetRow = Range(Cell).Row
 End Function


 Function GetColumn(Cell As String)
    GetColumn = Range(Cell).Column
 End Function

是的,我知道,但我的意思是什么类型的变量? - Eyal
@AnDrOiD =GetData("A2") 可以正常工作(从电子表格单元格运行时返回2)。 - Ioannis
尝试一下我发布的示例,看看是否适用于你。 - Dimitris Kalaitzis
@DimitrisKalaitzis 我应该在哪里编写 Sub 函数? - Eyal
这应该从另一个工作表中获取特定单元格的值:http://i.imgur.com/GJU6Duf.png 为什么它不起作用? - Eyal
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接