在尝试将一系列数据从excel复制到新的.txt文件时,我需要帮助 我已经到了创建文本文件的地步,但是我一直试图复制范围并将其粘贴到.txt文件中。 数据的格式必须为垂直格式,以便其他程序可以读取它。
答案 0 :(得分:1)
尝试一下
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