我使用SendKeys
Excel VBA功能将数据从Excel复制到记事本。
我希望避免使用sendkeys。
我有这段代码:
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
这只会将数据从Excel复制到记事本,但在Excel文件中进行一些更正后,我希望记事本中的数据从C2开始复制到Excel。
答案 0 :(得分:3)
这是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
答案 1 :(得分:2)
您可以使用文件系统对象写入文本文件:
keyword rank search_volume visability
1 A 1 1000 900
2 B 5 50000 25000
3 C 12 3500 0
有关详细信息,请参阅此处:https://technet.microsoft.com/en-us/library/ee198716.aspx
答案 2 :(得分:1)
有点太晚了,但您可以将数据复制到剪贴板并将其粘贴为文本(已测试并正常工作):
Dim r As Range
Set r = wb.Sheets(2).Range("C2:C" & lRow)
r.Copy
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.GetFromClipboard
Application.CutCopyMode = False
.PutInClipboard
End With
r.Select
r.NumberFormat = "@"
r.Worksheet.PasteSpecial "Text"
答案 3 :(得分:0)
这可能是可行的:
wb.Sheets(2).Range("C2:C" & lRow).Copy
*.csv
文件:Saving excel worksheet to CSV files with filename+worksheet name using VB 答案 4 :(得分:0)
'This macros may solve your problem
Sub SaveMySheetAsTextFile()
Sheets("Sheet1").Select
ActiveWorkbook.SaveAs Filename:="C:\mynotepadfile.txt", FileFormat:=xlText
End Sub
答案 5 :(得分:0)
尝试一下:
Sub SimpleVBAWriteToFileWithoutQuotes()
Open "c:\TEMP\Excel\out.txt" For Output As #1
Print #1, Application.ActiveSheet.Cells(2, 3)
Close #1
End Sub