mercredi 24 janvier 2018

Excel VBA - conditional export to TXT (various text files)

I have from the past got help of creating a file to export values using this thread:

Export Excel range to TXT stop at empty cell.

This works but doesn´t do exactly what I want. I have a list looking like this (with start from Column A):

enter image description here

What I want is that if Column C (Rename) has value Yes och Column E has value North it should do some thing and then export to txt.

It should depend of both Column C and E for what the outcome would become.

Example:

If Rename is Yes and Place is South --> Do this.
If Rename is No and Place is South --> Do another thing.
If Rename is Yes and Place is North --> It does another thing.

and so on...

Any sugestion how to begin?

Sub SaveToTXT()
Dim filename As String, lineText As String
Dim myrng As Range, i, j

filename = ThisWorkbook.path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"

Open filename For Output As #1

Set myrng = Range("A:B")

For i = 1 To myrng.Rows.Count
For j = 1 To myrng.Columns.Count

If IsEmpty(myrng.Cells(i, j)) = True Then Close #1
If myrng(i, 3).Value = "No" And myrng(i, 5).Value = "North" Then 'do something, no replace'
If myrng(i, 3).Value = "Yes" And myrng(i, 5).Value = "North" Then 'do something, yes replace'
If myrng(i, 3).Value = "No" And myrng(i, 5).Value = "South" Then 'do something, no replace'
If myrng(i, 3).Value = "Yes" And myrng(i, 5).Value = "South" Then 'do something, yes replace'
If myrng(i, 3).Value = "No" And myrng(i, 5).Value = "West" Then 'do something, no replace'
If myrng(i, 3).Value = "Yes" And myrng(i, 5).Value = "West" Then 'do something, yes replace'
If myrng(i, 3).Value = "No" And myrng(i, 5).Value = "East" Then 'do something, no replace'
If myrng(i, 3).Value = "Yes" And myrng(i, 5).Value = "East" Then 'do something, yes replace'
If myrng(i, 3).Value = "No" And myrng(i, 5).Value = "NorthEast" Then 'do something, no replace'
If myrng(i, 3).Value = "Yes" And myrng(i, 5).Value = "NorthEast" Then 'do something, yes replace'
If myrng(i, 3).Value = "No" And myrng(i, 5).Value = "SouthEast" Then 'do something, no replace'
If myrng(i, 3).Value = "Yes" And myrng(i, 5).Value = "SouthEast" Then 'do something, yes replace'
Exit Sub
End If

    lineText = IIf(j = 1, "", lineText & " ") & myrng.Cells(i, j)
Next j
Print #1, lineText
Next i
Close #1
End Sub

Edit/Addendum (cf. user comment): "What I want is that all that have the same match will be added to the same txt.file. ' I can only have a total of 12 files but all shouldn´t be created if the IF THEN isn´t a match. ' The txt-file should also have different names."

Aucun commentaire:

Enregistrer un commentaire