vba 将范围选择复制到文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19688269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy a range selection to text file
提问by gabx
I can not find a clean answer about copy/paste a range from Excel to a Notepad text file. What I tried ( a For Each Cell) does not give me the desired output (everything is in one column).
我找不到关于将范围从 Excel 复制/粘贴到记事本文本文件的明确答案。我尝试过的(一个 For Each Cell)没有给我想要的输出(所有内容都在一列中)。
This following code works well :
以下代码运行良好:
With Application
Selection.Copy
Shell "notepad.exe", 3
SendKeys "^v"
VBA.AppActivate .Caption
.CutCopyMode = False
End With
But I would like to save the file in a dedicated path and not having to deal manually with Notepad. My cells to copy are text, and the output has to be delimited with blancks and respects the rows & columns.
但我想将文件保存在专用路径中,而不必手动处理记事本。我要复制的单元格是文本,输出必须用空格分隔并尊重行和列。
I found solutions with copying the selection to another Woksheet, then saving it as text, but it sound to me rather hasardous for my workbook sanaty or heavy. My question can seems stupid but I really can't find a clean answer, and most important, a code I will understand.
我找到了将所选内容复制到另一个 Woksheet,然后将其另存为文本的解决方案,但对我来说,这对于我的工作簿健全或沉重来说相当麻烦。我的问题看起来很愚蠢,但我真的找不到一个干净的答案,最重要的是,我会理解的代码。
回答by user2140261
Sub writeCells()
Dim strPath As String
Dim strName As String
Dim FSO As Object
Dim oFile As Object
Dim c As Range
strName = "YourFileName.txt"
strPath = "C:\Your\Path\"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set oFile = FSO.CreateTextFile(strPath & strName)
For Each c In Selection
oFile.Write c.Value & " "
Next c
oFile.Close
End Sub
In this example A1:B10
is selected.
在这个例子中A1:B10
被选中。
so starting with a blank file:
所以从一个空白文件开始:
After running this macro and reopen the file I end up as below:
运行此宏并重新打开文件后,我最终如下所示: