Search code examples
excelvbaexcel-2007

How to export a column data in excel to a text file using a vba code?


I want to export the data contained in column H in an excel file using a vba code. I managed to get the code, but i want to modify it to allow me to choose the name and the directory to save it before creating it.Thanks in advance The code is

Sub Export()

Dim i As Long, derLig As Long, tabl

derLig = Range("H" & Cells.Rows.Count).End(xlUp).Row
tabl = Range("H1:H" & derLig)
Open "D:\CCP.txt" For Output As #1
For i = 1 To UBound(tabl, 1)
If tabl(i, 1) <> "" Then
Print #1, tabl(i, 1)
End If
Next
Close #1
MsgBox ("Le Fichier CCP A Eté Créé Dans Le Disque D")
End Sub

Solution

  • Option Explicit
    
    Sub Export()
    
        Dim i As Long, n As Long, derLig As Long, tabl
        Dim filename As String
        
        With ActiveSheet
            If WorksheetFunction.CountA(.Range("H:H")) = 0 Then
                MsgBox "pas de données à sauvegarder", vbCritical
                Exit Sub
            End If
            derLig = .Range("H" & Cells.Rows.Count).End(xlUp).Row
            tabl = .Range("H1:H" & derLig)
        End With
        
        filename = Application.GetSaveAsFilename
        If Len(filename) = 0 Then
            MsgBox "nom de fichier non valide", vbCritical
            Exit Sub
        End If
        
        Open filename For Output As #1
        For i = 1 To UBound(tabl, 1)
            If tabl(i, 1) <> "" Then
                Print #1, tabl(i, 1)
                n = n + 1
            End If
        Next
        Close #1
        MsgBox n & " lignes écrites dans " & filename, vbInformation
      
    End Sub