Excel 复制范围并将其直接粘贴到.txt文件

Excel 复制范围并将其直接粘贴到.txt文件,excel,vba,Excel,Vba,我需要帮助尝试将一系列数据从excel复制到一个新的.txt文件 我已经开始创建一个文本文件,但我一直在尝试复制范围并将其粘贴到.txt文件中。 数据格式需要垂直,以便其他程序能够读取数据。试试这个 Option Explicit 'Copy the contents of a worksheet, and save it as a new workbook as a .txt file Sub Sheet1_Tab() Dim wbSource As Workbook Dim wsSourc

我需要帮助尝试将一系列数据从excel复制到一个新的.txt文件 我已经开始创建一个文本文件,但我一直在尝试复制范围并将其粘贴到.txt文件中。 数据格式需要垂直,以便其他程序能够读取数据。

试试这个

Option Explicit

'Copy the contents of a worksheet, and save it as a new workbook as a .txt file
Sub Sheet1_Tab()
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim wbDest As Workbook
Dim fName As String

'References
Set wbSource = ActiveWorkbook
Set wsSource = ThisWorkbook.Sheets("Sheet1") 'Change as per your requirement
Set wbDest = Workbooks.Add

'Copy range on original sheet
'Assuming your range is contiguous.
wsSource.UsedRange.Copy

'Save in new workbook
wbDest.Worksheets(1).Cells(1, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Application.CutCopyMode = False

'Get file name and location
fName = ThisWorkbook.Path & "\Sheet1.txt"

'Save new tab delimited file
wbDest.SaveAs fName, xlText

wbDest.Close SaveChanges:=True

End Sub
您也可以使用记事本路线:

或者,下面的程序从工作表上的一系列单元格中获取要复制到剪贴板的值,将剪贴板内容获取为字符串,将该字符串保存到临时文件中,然后使用临时文件的内容打开
Notepad.exe

代码:

Option Explicit

Sub ThroughNotePadTxt()

    Dim rngDat As Range
    Dim strData As String
    Dim strTempFl As String

    ' copy some range values
    Set rngDat = Sheets("Sheet1").Range("A1:G20")' Change as per your requirement
    rngDat.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
    strTempFl = "C:\temp.txt" 'Change as per your reqirement. Directory to have permission to write the file
    With CreateObject("Scripting.FileSystemObject")
        ' true to overwrite existing temp file
        .CreateTextFile(strTempFl, True).Write strData
    End With

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

End Sub