非常简单:我有一个文本框,当用户点击Return键时,该文本框应写入Excel单元格。问题是对单元格的写入发生了两次,所以我得到了两个用户输入的条目。我已经检查过我只在TextBox中激活KeyPress而不是Form,并且还尝试了KeyDown / KeyUp事件以及相同的结果。我尝试了两种不同的键盘,并以相同的结果降低了键盘轮询速度。我还在一个消息框中添加了一个全局输出来跟踪例程被调用的次数,奇怪的是它说" 1"每次。
我很难过。
Private Sub vbKeyReturnNC(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim NewController As String
NewController = TextBox1.Text
If e.KeyChar = ChrW(13) Then
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
oExcel = New Excel.Application 'Create a new instance of Excel
My.Computer.FileSystem.CopyFile("C:\QA Controller Test Files\New Controller Template.xlsm", "C:\QA Controller Test Files\" & NewController & ".xlsm")
oExcel.Workbooks.Open("C:\QA Controller Test Files\" & NewController & ".xlsm")
oSheet = oExcel.Worksheets(1)
oSheet.Range("B1").Value = TextBox1.Text
oExcel.Visible = True 'Show it to the user
Count = Count + 1 'Count how many times this event triggers
MsgBox(Count) 'Output number of times run
oBook = Nothing 'Disconnect from Excel (let the user take over)
oExcel = Nothing
End If
End Sub
答案 0 :(得分:0)
您确定在某个地方没有添加第二个事件处理程序吗? sub上的Handles
子句自动添加处理程序。如果您在代码中手动添加了处理程序,则AddHandler
将附加第二个处理程序。这将使事件看起来像是两次射击。
答案 1 :(得分:0)
我的代码是
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
evKeyPressed(sender, e)
End Sub
Private Sub evKeyPressed(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
带有“句柄...”的第二个子似乎触发了两次。
谢谢布拉德!