excelvbacopyrange

Copy used range to text file


I want to:

I have:

Sub CreateAfile()

Dim pth As String
pth = ThisWorkbook.path
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Dim a As Object
Set a = fs.CreateTextFile(pth & "\Kommentar.txt", True)
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Kommentar")

Dim rng As Range
Set rng = sh.UsedRange
a.WriteLine (rng)
a.Close

End Sub

I get

run-time error '13' Mismatch

In line a.WriteLine (rng) the function doesn't accept range to be written.


Solution

  • Since your range is probably made up of several cells, you have to loop through them to get all the text into a string variable. If you use a Variant variable you can copy the values and automatically get an array with the correct dimensions of all the data in the cells, then loop it and copy the text:

    Function GetTextFromRangeText(ByVal poRange As Range) As String
        Dim vRange As Variant
        Dim sRet As String
        Dim i As Integer
        Dim j As Integer
    
        If Not poRange Is Nothing Then
    
            vRange = poRange
    
            For i = LBound(vRange) To UBound(vRange)
                For j = LBound(vRange, 2) To UBound(vRange, 2)
                    sRet = sRet & vRange(i, j)
                Next j
                sRet = sRet & vbCrLf
            Next i
        End If
    
        GetTextFromRangeText = sRet
    End Function
    

    Call the function in your code by replacing the a.WriteLine (rng) line with the following:

    Dim sRange As String
    sRange = GetTextFromRangeText(rng)
    Call a.WriteLine(sRange)