Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a range selection to text file

Tags:

excel

vba

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).

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.

like image 800
gabx Avatar asked Dec 03 '25 11:12

gabx


1 Answers

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.

so starting with a blank file:

enter image description here

After running this macro and reopen the file I end up as below:

enter image description here

like image 165
user2140261 Avatar answered Dec 05 '25 02:12

user2140261



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!