VBA-获取光标位置作为单元格地址 [英] VBA - Get cursor position as cell address

查看:1259
本文介绍了VBA-获取光标位置作为单元格地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以很好地用于以像素为单位检索光标位置:

I have the following code which works fine for retrieving the cursor position as pixels:

Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
' Create custom variable that holds two integers
Type POINTAPI
    Xcoord As Long
    Ycoord As Long
End Type

Sub GetCursorPosDemo()
    Dim llCoord As POINTAPI
    ' Get the cursor positions
    GetCursorPos llCoord
    ' Display the cursor position coordinates
    MsgBox "X Position: " & llCoord.Xcoord & vbNewLine & "Y Position: " & llCoord.Ycoord
End Sub

我希望它返回当前光标所在的单元格地址,或者返回Points中的坐标,因此我可以将其转换为地址.有可能吗?

I'd like it to return the cell address on which my cursor currently is, or perhaps the coordinates in Points, so I can convert it to an address. Is that possible?

推荐答案

使用ActiveWindow.RangeFromPoint获取单元地址.

Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
' Create custom variable that holds two integers
Type POINTAPI
    Xcoord As Long
    Ycoord As Long
End Type

Sub GetCursorPosDemo()
    Dim llCoord As POINTAPI
    Dim rng As Range
    ' Get the cursor positions
    GetCursorPos llCoord
    ' Display the cursor position coordinates
    'MsgBox "X Position: " & llCoord.Xcoord & vbNewLine & "Y Position: " & llCoord.Ycoord

    Set rng = GetRange(llCoord.Xcoord, llCoord.Ycoord)

    If Not rng Is Nothing Then
        MsgBox "Cell under mouse is :" & rng.Address
    Else
        MsgBox "Not a valid location."
    End If

End Sub

Function GetRange(x As Long, y As Long) As Range
    Set GetRange = ActiveWindow.RangeFromPoint(x, y)
End Function

这篇关于VBA-获取光标位置作为单元格地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆