将数据保存到文本文件

时间:2019-03-22 01:06:34

标签: excel vba

我有一个用于Excel VBA宏的代码,该代码运行良好,但是运行后,自动在键盘中关闭了Num Lock,有人在这里为我提供帮助吗?

Sub Tester()
With Application

    Selection.Copy
    Shell "notepad.exe", 3
    SendKeys "^v"
    SendKeys "^s"
    SendKeys "C:\Users\MDIMAMUDDIN\Desktop\abc.txt"                      '<<==== Change
    SendKeys "{ENTER}"
    SendKeys "%fx"
    VBA.AppActivate .Caption
    .CutCopyMode = False
End With
End Sub

1 个答案:

答案 0 :(得分:0)

似乎有一个excel bug可以在调用多个sendkey时关闭num lock。如果您的代码在模块或表单中,则可以将其添加到模块中:

Private Declare Sub keybd_event Lib "user32" ( _
ByVal bVk As Byte, _
ByVal bScan As Byte, _
ByVal dwFlags As Long, _
ByVal dwExtraInfo As Long)
Private Const VK_NUMLOCK = &H90
Private Const KEYEVENTF_KEYUP = &H2
Declare Function GetKeyState Lib "user32.dll" (ByVal nVirtKey As Long) As Integer

Sub NUM_On()  'Turn NUM-Lock on
  If Not (GetKeyState(vbKeyNumlock) = 1) Then
    keybd_event VK_NUMLOCK, 1, 0, 0
    keybd_event VK_NUMLOCK, 1, KEYEVENTF_KEYUP, 0
  End If
End Sub

然后从您的子目录中调用Num_on:

Sub Tester()
    With Application

        Selection.Copy
        Shell "notepad.exe", 3
        SendKeys "^v"
        SendKeys "^s"
        SendKeys "C:\Users\MDIMAMUDDIN\Desktop\abc.txt"                      '<<==== Change
        SendKeys "{ENTER}"
        SendKeys "%fx"
        VBA.AppActivate .Caption
        .CutCopyMode = False
    End With
    Module1.NUM_On
End Sub

如果您的代码在工作表代码部分中,那么您将必须创建一个模块并将代码放置在其中(您可以将测试器子放置在此处,但其他代码必须在模块中)。 / p>