将数据从 Excel 复制到记事本

3 excel vba notepad

我使用SendKeysExcel VBA 函数将数据从 Excel 复制到记事本。

我希望避免使用发送键。

我有这个代码:

sub test()

    dim wb as Workbook
    set wb = "C:\Documents\test.xlsx"
    wb.Sheets(2).Range("C2:C" & lRow).Copy
    myApp = Shell("Notepad.exe", vbNormalFocus)
    SendKeys "^v"
    Application.CutCopyMode = False
    wb.Sheets(2).Range("C2:C" & lRow).NumberFormat = "@"
 end sub
Run Code Online (Sandbox Code Playgroud)

这只是将数据从 Excel 复制到记事本,但在对 Excel 文件进行一些更正后,我希望将记事本中的数据从 C2 开始复制到 Excel。

Rob*_*zie 9

这是一个替代过程SendKeys

  • 从工作表上的一系列单元格中获取值

  • 复制到剪贴板

  • 获取剪贴板内容到一个字符串

  • 将该字符串保存到临时文件

  • 使用临时文件的内容打开 Notepad.exe

代码:

Option Explicit

Sub OpenNotepadWithTempFileWithClipboardContent()

    Dim rngData As Range
    Dim strData As String
    Dim strTempFile As String

    ' copy some range values
    Set rngData = Sheet3.Range("B1:B5")
    rngData.Copy

    ' get the clipboard data
    ' magic code for is for early binding to MSForms.DataObject
    With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
        .GetFromClipBoard
        strData = .GetText
    End With

    ' write to temp file
    strTempFile = "D:\temp.txt"
    With CreateObject("Scripting.FileSystemObject")
        ' true to overwrite existing temp file
        .CreateTextFile(strTempFile, True).Write strData
    End With

    ' open notepad with tempfile
    Shell "cmd /c ""notepad.exe """ & strTempFile & """", vbHide

End Sub
Run Code Online (Sandbox Code Playgroud)