Option Explicit
Public Sub Whatever()
Dim FirstRow As Long, LastRow As Long, lastcol As Long
Dim towrite As String
Dim i As Integer
Dim arr As Variant
'Need to setup named range properly here for variable row data
Application.Goto Reference:="CHK"
FirstRow = Selection(1).Row
LastRow = Selection(Selection.Count).Row
'get count of used rows
Selection.End(xlToRight).Select
lastcol = Selection(Selection.Count).Column
'get count of used columns
Application.Goto Reference:="CHK"
Selection.End(xlUp).Select
For i = FirstRow To LastRow
Selection.Offset(1, 0).Select
towrite = Selection.Value2
'cell comparison
If UCase(towrite) = "Y" Then
arr = Selection.EntireRow.Value
WriteTextFile arr, lastcol
End If
Next i
End Sub
Public Sub WriteTextFile(ByVal arr As Variant, lastcol As Long)
Dim myfile As String, writestr As String, exist As String
Dim fnum As Integer, i As Integer
writestr = ""
myfile = "d:\" & "sample.txt"
exist = Dir(myfile)
If Len(exist) = 0 Then
fnum = FreeFile()
'create new file if doesnt exist
Open myfile For Output As fnum
For i = 1 To lastcol
writestr = writestr & ctstr(arr(1, i)) & ","
Next i
Print #fnum, writestr
Close #fnum
Else
fnum = FreeFile()
Open myfile For Append As fnum
'open existing file
For i = 1 To lastcol
writestr = writestr & ctstr(arr(1, i)) & ","
Next i
Print #fnum, writestr
Close #fnum
End If
End Sub
Public Function ctstr(ByVal arrstr As Variant)
'Do somethin extra here for handling decimal points
If IsNumeric(arrstr) Then
'Str conversion, good to have to get locale-independent data
ctstr = Str(arrstr)
Else
ctstr = arrstr
End If
End Function