获取光标在单元格中的位置

我正在尝试在公式栏中创build一个自定义的右键单击菜单(右键单击时出现的单元格,例如键入内容)。 我已经设法得到我想要的button,但我找不到如何find光标位于单元格内的位置。

例如,如果光标位于单元格中的第5个字符之后,我如何确定BeforeRightClick事件发生之前或之前? 我唯一发现的是相反的问题。 将光标放在单元格的特定部分,使用SendKeys:

'=================================================================================== '- MOVE CURSOR IN THE FORMULA BAR AS REQUIRED '- Brian Baulsom September 2007 '=================================================================================== Sub test() Dim c As Integer c = 3 '------------------------------------------------------------------------------ Range("A1").Select ' select cell SendKeys "{F2}", True ' activate formula bar. cursor is to right of contents. DoEvents '------------------------------------------------------------------------------ '- move cursor 3 characters to the left in the formula bar '- or in the cell if Tools/Options/Edit .. "Edit directly in cell" is checked SendKeys "{LEFT " & CStr(c) & "}", True ' ="{LEFT 3}" DoEvents End Sub '----------------------------------------------------------------------------------- source: http://www.mrexcel.com/forum/excel-questions/282172-setting-cursor-position-cell-text-using-visual-basic-applications.html 

最终目标是在input单元格的同时插入一些标准的子string。 例如,我想要插入[hi this is standard string X-XXX-XXXX]通过使用右键单击我键入单元格中。

编辑:

我尝试使用sendkeys直接发送我的string,但我只是从Excel中得到一个“平”的声音,表明这是不可能的。 这就是我曾经试过的:

 With fbar.Controls.add(Temporary:=True, Type:=msoControlButton, Before:=1) .BeginGroup = False .FaceId = 267 .Caption = wsLabels.GetLabel("rcRefMoM") .OnAction = "'" & ThisWorkbook.Name & "'!'rcAddRef2 '" End With Function rcAddRef2() SendKeys (" [Ref:X \NAME]") End Function 

编辑2:其实它甚至没有进入我的rcAddRef2函数,它只是直接ping,因为我在编辑模式。 如果我把它放在那里,它不会激活一个断点。 所以Sendkeys可能不是问题,就像让函数运行一样。

它在单元格命令栏中正常工作,如果我尝试它,所以我有点茫然:

 'This runs With cbar.Controls.add(Temporary:=True, Type:=msoControlButton, Before:=1) .BeginGroup = False .FaceId = 267 .Caption = wsLabels.GetLabel("rcRefMoM") .OnAction = "'" & ThisWorkbook.Name & "'!'rcAddRef2 '" End With 

一旦进入单元格编辑模式,就没有事件被触发到VBA中。 虽然可能会插入一些更深的Windows dll代码,但更好的select是使用带有TextBox对象的UserForm:

https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.controls.textbox.aspx

具体而言,您要截获TextChanged事件:

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged.aspx

在该对象上触发了几十个事件,包括KeyDown,KeyPress和KeyUp,所以我相信你可以find最适合你的场景。