excel 2010 vba 发送按键模拟点击编辑栏

excel 2010 vba send keys to simulate clicking the formula bar

Google 没有给我我想要的东西,我想也许 SO 可能有答案。

我没有使用输入框或用户提示来询问用户将存储在单元格中的信息,而是寻找一些代码来模拟单击编辑栏。我目前正在使用带有 "F2" 的 sendkeys 方法来允许用户将信息输入到选定的单元格中。查看公式栏会容易得多,而不是查看海量数据中的单个单元格。

Sub CopyTemplate()

'ActiveWorkbook.Save
Worksheets("HR-Cal").Activate
Dim rng As Range
Dim trng As Range
Dim tco As String
'Use the InputBox select row to insert copied cells
Set rng = Application.InputBox("select row to paste into", "Insert template location", Default:=ActiveCell.Address, Type:=8)
If rep = vbCancel Then
End If

startrow = rng.Row
'  MsgBox "row =" & startrow
Range("AG2") = startrow

Application.ScreenUpdating = False

'copy template block
Range("C6").End(xlDown).Select
Range("AG1") = ActiveCell.Row

tco = "A5:AN" & Range("AG1")
Range(tco).Select
Selection.Copy

Range("A" & Range("AG2")).Activate
Selection.Insert Shift:=xlDown

Range("c100000").End(xlUp).Select
Selection.End(xlUp).Select
'select first value

Range("AG1:AG2").ClearContents

Application.ScreenUpdating = True

SendKeys "{F2}"
SendKeys "{BS}"

End Sub

当代码运行时,这就是用户看到的内容(col 2 col 2621)

我不相信 "activate" 公式栏只有一个按键。可能有一种方法可以处理多个按键事件,例如 <alt><tab><tab>...~nine years later and a couple of other keys~...<tab><tab>

更快更直接的方法是关闭 "EditDirectlyInCell" 设置:

Application.EditDirectlyInCell = False

这会在您发送键时将光标移至编辑栏 F2

您可以在工作簿的代码 Workbook_Open() 上关闭此功能:

Private Sub Workbook_Open()
    Application.EditDirectlyInCell = False
End Sub

也许在 Workbook_BeforeClose() 上您可以重新启用该设置,这样您就不会更改它们的默认值:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Application.EditDirectlyInCell = True
End Sub

也许这会有所帮助,我将 Application.EditDirectlyInCell 设置为 false,然后再进入 单元格编辑 ,然后调用 DoEvents 在将 EditDirectlyInCell 返回为 true

之前
Sub EditRange(ByVal Target As Range)          'so any change in target would not affect
                                              'the caller's variable

    Set Target = Target.Areas(1).Resize(1, 1) 'to make sure the target is single cell

    Target.Worksheet.Activate                 'to make sure the worksheet is active

    Target.Activate                           'activate the designated cell

    Application.EditDirectlyInCell = False    'turn cell editing to false, any attempt _
                                               to edit cell will be done in formula bar

    SendKeys "{F2}"                           'send F2 to start editing the cell

    DoEvents                                  'make sure every command is fully executed

    Application.EditDirectlyInCell = True     'return in cell editing to default value
End Sub