Search code examples
excelvbatxt

Create a text file and paste some specific data from a sheet into a renamed sheet


I have written a basic code in VB to filter out a specific text ("FIN") which I have to write in a .txt file and rename it using string from a cell in the same workbook but different sheet. Below is the code i prepared to filter out and it works but I am stuck at the saving and renaming part.

Sub SAVE()
Dim WS1 As Worksheet, WS2 As Worksheet
Dim Lastrow As Long
Set WS1 = Sheets("WORKING")
Set WS2 = Sheets("FINAL")

WS2.Cells.Delete
WS1.AutoFilter.ShowAllData
WS1.Range("B1:C50000").AutoFilter Field:=2, Criteria1:="<>FIN"
Lastrow = WS1.Cells(Rows.Count, "B").End(xlUp).Row
WS1.Range("B1:B" & Lastrow).SpecialCells(xlCellTypeVisible).Copy WS2.Range("A1")
Sheets("FINAL").Select
Range("A1:A & Lastrow").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Solution

  • Sub SAVE_LM()
    
    'Define all variables
    
    Dim WS1 As Worksheet, WS2 As Worksheet
    Dim LastRow As Long
    Set WS1 = Sheets("WORKING")
    Set WS2 = Sheets("FINAL")
    Const Forwriting = 2
    Dim EXCELPATH As String
    Dim NAME As String
    
    'File name create from name
    NAME = ThisWorkbook.Names("NAME").RefersToRange.Value & ".FHX"
    
    'FIle path same as the excel path
    EXCELPATH = Application.ThisWorkbook.PATH
    
    'Create .txt file and save as .fhx
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Dim FileName As String
    FileName = NAME
    strfullname = objFSO.BuildPath(EXCELPATH, FileName)
    Set objFile = objFSO.CreateTextFile(strfullname)
    objFile.Close
    
    'Write all the code for fhx from the working sheet into the Final_FHX sheet 
    removing FIN
    WS2.Cells.Delete
    WS1.AutoFilter.ShowAllData
    WS1.Range("B1:C20000").AutoFilter Field:=2, Criteria1:="<>FIN"
    LastRow = WS1.Cells(Rows.Count, "B").End(xlUp).Row
    WS1.Range("B1:B" & LastRow).SpecialCells(xlCellTypeVisible).Copy WS2.Range("A1")
    Sheets("FINAL_FHX").Select
    Range("A1:A" & LastRow).Select
    Range(Selection, Selection.End(xlDown)).Select
    
    'Write the code from FINAL into the .TXT file and save as .FHX file
    Dim PATH As String
    PATH = objFSO.BuildPath(EXCELPATH, FileName)
    Open PATH For Output As #1
            For i = 1 To LastRow
                Print #1, Cells(i, 1)
                Next i
        Close #1
        
    'Change focus to Info sheet
    ThisWorkbook.Worksheets("INFO").Activate
    
    
    End Sub