Save Excel Row Via Vba Loop - excel

Hello everyone ı want to save each row of my excel file as a batch file.
I did it for second row but cant do it in loop.
Sub ExportFile()
Dim objFSO, objFile
Dim fileName As String
Dim RootPath As String
Dim text_comm As String
Dim OutputString: OutputString = ""
fileName = Cells([2], [1])
text_comm = Cells([2], [5])
RootPath = "C:\Users\DELL\Desktop\PDM SOLID DOSYA YOLU\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(RootPath + fileName + ".bat")
Do
OutputString = OutputString & Replace((text_comm), Chr(10), vbNewLine) & vbNewLine
objFile.Write (OutputString)
fileName = Cells([2] + 1, [1]) #Wrong
text_comm = Cells([2] + 1, [5]) #Wrong
Loop Until IsEmpty(text_comm)
Set objFile = Nothing
Set objFSO = Nothing
End Sub

Export Cell Contents As TextFiles
It is assumed that the first column ("A") contains the file base names, and that the fifth column ("E") contains the codes (each code in one cell).
Option Explicit
Sub ExportFiles()
Const RootPath As String = "C:\Users\DELL\Desktop\PDM SOLID DOSYA YOLU\"
Const FirstRow As Long = 2
Const NameCol As Long = 1
Const CodeCol As Long = 5
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim r As Long: r = FirstRow
Dim FileBaseName As String: FileBaseName = ws.Cells(r, NameCol)
Dim text_comm As String: text_comm = ws.Cells(r, CodeCol)
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim fsoFile As Object
Dim OutputString As String
Do Until Len(text_comm) = 0
Set fsoFile = fso.CreateTextFile(RootPath & FileBaseName & ".bat")
OutputString = Replace(text_comm, Chr(10), vbNewLine) & vbNewLine
fsoFile.Write OutputString
r = r + 1
FileBaseName = ws.Cells(r, NameCol)
text_comm = ws.Cells(r, CodeCol)
Loop
MsgBox "Files created.", vbInformation
End Sub

text_comm is merge former cell for each loop
Sub ExportFile()
Dim objFSO, objFile
Dim fileName As String
Dim RootPath As String
Dim text_comm As String
Dim OutputString: OutputString = ""
Dim RowIndex As String
RowIndex = 2
Do
fileName = Cells([RowIndex], [1])
text_comm = Cells([RowIndex], [5])
RootPath = "C:\Users\DELL\Desktop\PDM SOLID DOSYA YOLU\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(RootPath + fileName + ".bat")
OutputString = OutputString & Replace((text_comm), Chr(10), vbNewLine) & vbNewLine
objFile.Write (OutputString)
RowIndex = RowIndex + 1
Loop Until RowIndex = 6
Set objFile = Nothing
Set objFSO = Nothing
End Sub

Your loop needs to iterate through all rows. Currently it only processes the first row and is stuck there infinitly. You will have to keep record of the current row being processed RowIndex and increment it after each time.
Here is one way to fix your loop:
Dim RowIndex As Integer : RowIndex = 1
Do
OutputString = OutputString & Replace((text_comm), Chr(10), vbNewLine) & vbNewLine
objFile.Write (OutputString)
fileName = Cells([2] + RowIndex, [1])
text_comm = Cells([2] + RowIndex, [5])
RowIndex = RowIndex + 1
Loop Until IsEmpty(text_comm)

Related

For each issue, run-time error 6, overflow

the below code is working perfectly but when i added the "'" code the code will stop after n number of loop related for each (rng1) giving an error of overflow run-time error 6
Appreciate if you can help me and if there is any possibility to optimize the code, thank you
the below code is working perfectly but when i added the "'" code the code will stop after n number of loop related for each (rng1) giving an error of overflow run-time error 6
Appreciate if you can help me and if there is any possibility to optimize the code, thank you
Sub Count()
Dim myPath As String
Dim myFile As String
Dim FldrPicker As FileDialog
Dim sh As Worksheet
Dim i As Integer
Dim j As Integer
Dim Count As Integer
Dim CountRecords As String
Dim FilePath As String
Dim UniquePercentage As Integer
Dim SumOfUniqueness As Integer
Dim CountOfUniqueness As Integer
Dim rng As Range
Dim rng1 As Range
Dim LastPosition As Integer
Set sh = ThisWorkbook.Sheets(1)
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Please Select Folder"
.AllowMultiSelect = False
.ButtonName = "Confirm"
If .Show = -1 Then
myPath = .SelectedItems(1) & "\"
Else
End
End If
End With
sh.Cells.ClearContents
myFile = Dir(myPath)
i = 1
Do While myFile <> ""
sh.Cells(1, 1) = "Table Name"
sh.Cells(i + 1, 1) = myFile
sh.Cells(1, 2) = "Count of records"
sh.Cells(1, 3) = "Uniqueness"
Count = Count + 1
myFile = Dir
i = i + 1
Loop
j = 1
For i = 1 To Count
sh.Activate
Worksheets(1).Activate
FilePath = myPath & Range("A" & j + 1).Value
Workbooks.Open FilePath
Worksheets("Properties").Activate
CountRecords = Sheets("Properties").Range("C15").Value
Worksheets("Column Profile").Activate
LastPosition = Range("D10").End(xlDown).Row - 2
For Each rng In Range("D10:D" & LastPosition)
rng.Value = Replace(rng, "-", "0")
rng.Value = CInt(rng)
Next rng
'For Each rng1 In Range("E10:E" & LastPosition)
'rng1.Value = Replace(rng1, "-", "0")
'rng1.Value = CInt(rng1)
'Next rng1
CountOfUniqueness = WorksheetFunction.CountIf(Range("E10:E" & LastPosition), 0)
SumOfUniqueness = WorksheetFunction.Sum(Range("D10:D" & LastPosition))
UniquePercentage = SumOfUniqueness / CountOfUniqueness
ActiveWorkbook.Close (False)
sh.Activate
Worksheets(1).Activate
Range("B" & j + 1).Value = CountRecords
Range("C" & j + 1).Value = UniquePercentage
j = j + 1
Next i
If i = 1 Then
MsgBox("There are no items in this folder:" & Dir(myPath))
End If
End Sub

Hyperlinks sub folders file

Hello everyone yesterday ı try to do Save Excel Row Via Vba Loop, now my problem is give hyplinks that file via macro.
I try to explain in photo and my codes are below
Sub Hyperlinks()
Dim wks As Worksheet
Dim hl As Hyperlink
Const RootPath As String = "X:\EVEREST-2\EVEREST ERP\ÜRETİM\PDM SOLID DOSYA YOLU\"
Const SeriCol As Long = 3
Const NameCol As Long = 4
Const YearCol As Long = 24
Set wks = ActiveSheet
Dim r As Long: r = FirstRow
Dim FileBaseName As String: FileBaseName = ws.Cells(r, SeriCol)
Dim hl_name As String: hl_name = ws.Cells(r, NameCol)
Dim year As String: year = ws.Cells(r, YearCol)
Do Until Len(hl_name) = 0
wks.Hyperlinks.Add ws.Cells(r, NameCol), Address:=(RootPath & year & "\" & FileBaseName & ".bat"TextToDisplay:=hl_name)
r = r + 1
Loop
MsgBox "Hyperlinks created.", vbInformation End sub
Create Hyperlinks
' *** You want to reference the model cell before and at the end of the loop.
A Quick Fix
Option Explicit
Sub CreateHyperlinks()
Const RootPath As String = "X:\EVEREST-2\EVEREST ERP\ÜRETIM\PDM SOLID DOSYA YOLU\"
Const YearCol As String = "X"
Const SerialCol As String = "C"
Const ModelCol As String = "D"
Const FirstRow As Long = 2
Dim wks As Worksheet: Set wks = ActiveSheet ' improve!
Dim r As Long: r = FirstRow
Dim ModelCell As Range: Set ModelCell = wks.Cells(r, ModelCol) ' ***
Dim FilePath As String
Dim YearPath As String
Dim Serial As String
Do Until Len(CStr(ModelCell.Value)) = 0
YearPath = CStr(wks.Cells(r, YearCol)) & "\"
Serial = CStr(wks.Cells(r, SerialCol))
FilePath = RootPath & YearPath & Serial & ".bat"
wks.Hyperlinks.Add Anchor:=ModelCell, Address:=FilePath
r = r + 1
Set ModelCell = wks.Cells(r, ModelCol) ' ***
Loop
MsgBox "Hyperlinks created.", vbInformation
End Sub
There is a comma missing between ".bat" and TextToDisplay:
Address:=(RootPath & year & "\" & FileBaseName & ".bat"TextToDisplay:=hl_name)
Note: There is no need to use the TextToDisplay parameter when the display text is the same as the anchor cell value.
Refactored Code
Sub Hyperlinks()
Dim wks As Worksheet
Dim hl As Hyperlink
Const RootPath As String = "X:\EVEREST-2\EVEREST ERP\ÜRETIM\PDM SOLID DOSYA YOLU\"
Const SeriCol As Long = 3
Const NameCol As Long = 4
Const YearCol As Long = 24
Set wks = ActiveSheet
Dim r As Long: r = FirstRow
Dim FileBaseName As String: FileBaseName = ws.Cells(r, SeriCol)
Dim year As String: year = ws.Cells(r, YearCol)
Dim Address As String
Do Until Len(hl_name) = 0
Address = RootPath & year & "\" & FileBaseName & ".bat"
wks.Hyperlinks.Add ws.Cells(r, NameCol), Address:=Address
r = r + 1
Loop
MsgBox "Hyperlinks Added"
End Sub
ı fix it now it works
Sub Hyperlinks1()
Dim hl As Hyperlink
Const RootPath As String = "X:\EVEREST-2\EVEREST ERP\ÜRETİM\PDM SOLID DOSYA YOLU\"
Const SeriCol As Long = 3
Const NameCol As Long = 4
Const YearCol As Long = 24
Dim ws As Worksheet: Set ws = ActiveSheet
Dim r As Long: r = 4
Dim FileBaseName As String: FileBaseName = ws.Cells(r, SeriCol)
Dim hl_name As String: hl_name = ws.Cells(r, NameCol)
Dim year As String: year = ws.Cells(r, YearCol)
year = Right(year, 4)
Do Until Len(hl_name) = 0
With ws
.Hyperlinks.Add Anchor:=.Cells(r, NameCol), _
Address:=RootPath & year & "\" & FileBaseName & ".bat", _
ScreenTip:="Click to open 3D Solid File", _
TextToDisplay:=hl_name
End With
r = r + 1
FileBaseName = ws.Cells(r, SeriCol)
hl_name = ws.Cells(r, NameCol)
year = ws.Cells(r, YearCol)
year = Right(year, 4)
Loop
MsgBox "Hyperlinks created.", vbInformation
End Sub

Why does my VBA macro stop after opening and closing a few hundred CSV files?

I've written a macro that downloads zip files containing CSVs from a website. The downloading and unzipping is going perfectly, however when I try to loop through the CSVs searching for the occurrence of a specific string, the macro simply quits after opening about a thousand. There is no error message, it simply stops working, leaving the last CSV it was working on open.
Here is my code:
Sub OpenSearch()
Dim ROW, j As Integer
Workbooks.Open Filename:=FileNameFolder & FileListCSV(i)
For j = 1 To 7
ROW = 3
Do Until IsEmpty(Cells(ROW, 6))
If Cells(ROW, 6) = WantedID(j, 1) Then
MsgBox "WE HAVE A MATCH!"
End If
ROW = ROW + 1
Loop
Next j
Workbooks(FileListCSV(i)).Close False
Kill FileNameFolder & FileListCSV(i)
End Sub
I did not include the main module that calls the this sub and downloads and unzips the files, because on its own, that works perfectly. It only stops working when the sub I copied here is being called.
The Filename comes from a public variable defined in the main module, WantedID contains the strings I need to find in the CSVs.
I've tried to put Application.Wait in the first line, but it did not solve the problem. Also how far the macro gets is completely random. It never stops after the same number of CSVs opened and closed.
UPDATE: Here is the code (parent sub) for the downloading and unzipping. I did not come up with this on my own, but copied it from an online source I cannot recall:
Public FileListCSV(1 To 288) As String
Public i As Integer
Public FileNameFolder As Variant
Public WantedID As Variant
Sub DownloadandUnpackFile()
Dim myURL As String
Dim YearNUM As Integer
Dim MonthNUM As Integer
Dim StarMonth, EndMonth As Integer
Dim DayNUM As Integer
Dim YearSTR As String
Dim MonthSTR As String
Dim DaySTR As String
Dim FixURL As String
Dim TargetFileName As String
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim DefPath As String
Dim strDate As String
Dim StrFile As String
Dim FileList(1 To 288) As String
Application.ScreenUpdating = False
FixURL = "http://www.nemweb.com.au/REPORTS/ARCHIVE/Dispatch_SCADA PUBLIC_DISPATCHSCADA_"
WantedID = Range(Cells(2, 1), Cells(8, 1))
YearNUM = 2016
StarMonth = 12
EndMonth = 12
For YearNUM = 2015 To 2016
For MonthNUM = StarMonth To EndMonth
For DayNUM = 1 To 31
YearSTR = CStr(YearNUM)
If MonthNUM < 10 Then
MonthSTR = "0" & CStr(MonthNUM)
Else:
MonthSTR = CStr(MonthNUM)
End If
If DayNUM < 10 Then
DaySTR = "0" & CStr(DayNUM)
Else:
DaySTR = CStr(DayNUM)
End If
myURL = FixURL & YearSTR & MonthSTR & DaySTR & ".zip"
Cells(1, 1) = myURL
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.Send
myURL = WinHttpReq.ResponseBody
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.ResponseBody
TargetFileName = "C:\Users\istvan.szabo\Documents \Basslink\AEMO RAW DATA\RAWRAW\" & YearSTR & MonthSTR & DaySTR & ".zip"
oStream.SaveToFile (TargetFileName)
oStream.Close
End If
'try unzippin'
Fname = TargetFileName
If Fname = False Then
'Do nothing
Else
'Root folder for the new folder.
'You can also use DefPath = "C:\Users\Ron\test\"
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
FileNameFolder = "C:\Users\istvan.szabo\Documents\Basslink\AEMO RAW DATA\RAWRAW\" & YearSTR & MonthSTR & DaySTR
'Make the normal folder in DefPath
MkDir FileNameFolder
'Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
i = 1
StrFile = Dir(FileNameFolder & "\")
Do While Len(StrFile) > 0
FileList(i) = FileNameFolder & "\" & StrFile
FileListCSV(i) = Left(StrFile, Len(StrFile) - 3) & "csv"
StrFile = Dir
i = i + 1
Loop
'unzip the unzipped
For i = 1 To 288
Fname = FileList(i)
If Fname = False Then
'Do nothing
Else:
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
FileNameFolder = "C:\Users\istvan.szabo\Documents\Basslink\AEMO RAW DATA\"
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
Call OpenSearch
End If
Next i
End If
Next DayNUM
Next MonthNUM
StarMonth = 1
EndMonth = 5
Next YearNUM
Application.ScreenUpdating = True
End Sub
You could check the file without opening it. That would save you time and resources. Here is a quick draw of the code I would use:
Sub OpenSearch()
Dim ROW, j As Integer
Dim fileID
Dim buf As String
Dim tmp As Variant
Open FileNameFolder & FileListCSV(i) For Input As #1
For j = 1 To 7
ROW = 3
Do Until EOF(1)
Line Input #1, buf
'Remove double quotes
buf = Replace(buf, """", "")
'Split line to a array
tmp = Split(buf, ",")
'5 is the 6th column in excel tmp index starts with 0
fileID = tmp(5)
If fileID = WantedID(j, 1) Then
MsgBox "WE HAVE A MATCH!"
End If
ROW = ROW + 1
Loop
Next j
Close #1
Kill FileNameFolder & FileListCSV(i)
End Sub
EDIT: Also try to add a resource cleanup code, for example: Set WinHttpReq = Nothing, Set oStream = Nothing etc.
In line with other advice in the comments: -
You should close of resources when you are done with them using Set WinHttpReq = Nothing for example. This can avoid memory problems that are similar to the issue you are seeing.
It is also advisable to remove On Error Resume Next. This is hiding errors and you may well be missing results that you need. It would also allow for more information during errors.
I took your two code blocks and wrote them into one that I believe will be stable during running and make it to the end, Run this and let us know if it did resolve the issue. I did it this way as there was a lot of small changes that went towards what I suspect will be more stable and make it to the end.
Sub DownloadandUnpackFile()
Dim FSO As New FileSystemObject
Dim DteDate As Date
Dim Fl As File
Dim Fl_Root As File
Dim Fldr As Folder
Dim Fldr_Root As Folder
Dim LngCounter As Long
Dim LngCounter2 As Long
Dim oApp As Object
Dim oStream As Object
Dim oWinHttpReq As Object
Dim RngIDs As Range
Dim StrURL As String
Dim StrRootURL As String
Dim VntFile As Variant
Dim VntFolder As Variant
Dim VntRootFile As Variant
Dim VntRootFolder As Variant
Dim WkBk As Workbook
Dim WkSht As Worksheet
'This will speed up processing, but you might not see progress while it is working
Application.ScreenUpdating = False
'Set variables
StrRootURL = "http://www.nemweb.com.au/REPORTS/ARCHIVE/Dispatch_SCADA/PUBLIC_DISPATCHSCADA_"
'You should be a little more explicit here for clarity, refernce a worksheet
'E.g. StrID = ThisWorkbook.Worksheets("Sheet1").Range(Cells(2, 1), Cells(8, 1))
Set RngIDs = Range(Cells(2, 1), Cells(8, 1))
Set oWinHttpReq = CreateObject("Microsoft.XMLHTTP")
Set oApp = CreateObject("Shell.Application")
'Loop from 21/Feb/2015 to today
For DteDate = CDate("21/Feb/2015") To Date
StrURL = StrRootURL & Format(DteDate, "YYYYMMDD") & ".zip"
Debug.Print StrURL
oWinHttpReq.Open "GET", StrURL, False
oWinHttpReq.Send
StrURL = oWinHttpReq.ResponseBody
If oWinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write oWinHttpReq.ResponseBody
VntRootFile = Environ("UserProfile") & "\Documents\Basslink\AEMO RAW DATA\RAWRAW\" & Format(DteDate, "YYYYMMDD") & ".zip"
oStream.SaveToFile VntRootFile
oStream.Close
Set oStream = Nothing
VntRootFolder = Environ("UserProfile") & "\Documents\Basslink\AEMO RAW DATA\RAWRAW\" & Format(DteDate, "YYYYMMDD") & "\"
FSO.CreateFolder VntRootFolder
oApp.Namespace(VntRootFolder).CopyHere oApp.Namespace(VntRootFile).Items
Set Fldr_Root = FSO.GetFolder(VntRootFolder)
'Unzip the zipped zips
For Each Fl_Root In Fldr_Root.Files
If Right(LCase(Fl_Root.Name), 4) = ".zip" Then
VntFolder = Fl_Root.ParentFolder & "\" & Left(Fl_Root.Name, Len(Fl_Root.Name) - 4) & "\"
FSO.CreateFolder VntFolder
VntFile = Fl_Root.Path
oApp.Namespace(VntFolder).CopyHere oApp.Namespace(VntFile).Items
Set Fldr = FSO.GetFolder(VntFolder)
For Each Fl In Fldr.Files
If Right(LCase(Fl.Name), 4) = ".csv" Then
Set WkBk = Application.Workbooks.Open(Fl.Path)
Set WkSht = WkBk.Worksheets(1)
For LngCounter = 1 To RngIDs.Rows.Count
LngCounter2 = 1
Do Until WkSht.Cells(LngCounter2, 6) = ""
If WkSht.Cells(LngCounter2, 6) = RngIDs.Cells(LngCounter, 1) Then
Debug.Print "FOUND: " & Fl.Name & ": " & WkSht.Cells(LngCounter2, 6).Address
End If
LngCounter2 = LngCounter2 + 1
Loop
Next
Set WkSht = Nothing
WkBk.Close 0
Set WkBk = Nothing
End If
DoEvents
Next
Set Fldr = Nothing
End If
Next
Fldr_Root.Delete True
Set Fldr_Root = Nothing
FSO.DeleteFile VntRootFile, True
End If
DoEvents
Next
Set oApp = Nothing
Set oWinHttpReq = Nothing
Set RngIDs = Nothing
Application.ScreenUpdating = True
End Sub
Changes I have made: -
I used early binding to FileSystemObject simply to make it easier
to write up. You will need the 'Windows Scripting Runtime' reference
added (Tools > References > tick 'Windows Scripting Runtime')
I iterated through dates as a single loop rather then three loops of
strings working as a date
I set IDs to be a range and note a variant
I opened references once, reuse them (i.e. oApp), and then close
them
I added DoEvents to give time back to the computer to run anything it
may need to, this maintains a health system.
I used Debug.Print to add information to the immediate window instead
of msgbox, but you should really list the finds out in a separate
worksheet, (debug.print has a size limit so you may end up only
seeing X number of results as others are truncated off.

Split ExcelSheet after separator

I have an Excel file, in the first sheet I have on column A some text delimited by a separator, like this:
Column A
--------
Text line 1.1
Text line 1.2
Text line 1.3
***
Text line 2.1
Text line 2.2
Text line 2.3
***
Text line 3.1
I like to split the content after the *** separator and put each piece in a separate file with only one sheet. The name of the files should be the first line of the each section.
I need to be able to copy with the formatting, colors, etc.
This is the function but is not copying the formatting...
Private Function AImport(ThisWorkbook As Workbook) As Boolean
Dim height As Long
Dim fileName As String
Dim startLine As Long
Dim endLine As Long
Dim tmpWs As Worksheet
Dim AnError As Boolean
With ThisWorkbook.Worksheets(1) 'sheet name "Sheet1"
height = .Cells(.rows.Count, 2).End(xlUp).row
startLine = 6
nr = 1
For i = startLine + 1 To height
If InStr(.Cells(i, 2).Value, "***") > 0 Then
separate = i
a = Format(nr, "00000")
fileName = "File" & a
endLine = separate - 1
.rows(startLine & ":" & endLine).Copy
Set tmpWs = ThisWorkbook.Worksheets.Add
tmpWs.Paste
tmpWs.Select
tmpWs.Copy
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs fileName:=ThisWorkbook.path & "\Output\" & fileName & " .xls", FileFormat:=xlExcel8, CreateBackup:=False 'xlOpenXMLWorkbookMacroEnabled
ActiveWorkbook.Close
tmpWs.Delete
'update next start line
startLine = separate + 1
nr = nr + 1
End If
Next i
End With
If AnError Then
MsgBox "Errors detected in " & ThisWorkbook.Name & "! Check LogFile.txt file for details. Execution stopped!", vbExclamation, inputWb.Name
AImport = False
Else:
Application.StatusBar = "Workbook check succesfully completed. Executing macro..."
AImport = True
End If
ThisWorkbook.Close
End Function
Just give out a workable solution, surely not a good one
Sub testing()
Dim height As Long
Dim fileName As String
Dim startLine As Long
Dim endLine As Long
Dim tmpWs As Worksheet
With ThisWorkbook.Worksheets("Sheet2") ' Input your sheet name here
height = .Cells(.Rows.Count, 1).End(xlUp).Row
startLine = 3
For i = 2 To height
If InStr(.Cells(i, 1).Value, "***") > 0 Then
separate = i
fileName = .Cells(startLine, 1).Value
endLine = separate - 1
.Rows(startLine & ":" & endLine).Copy
Set tmpWs = ThisWorkbook.Worksheets.Add
tmpWs.Paste
tmpWs.Select
tmpWs.Copy
Application.DisplayAlerts = False
' in the following line, replace the file path with your own
ActiveWorkbook.SaveAs fileName:="H:\" & fileName & " .xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ActiveWorkbook.Close
tmpWs.Delete
'update next start line
startLine = separate + 1
End If
Next i
'handline the last section here
endLine = height
fileName = .Cells(startLine, 1).Value
.Rows(startLine & ":" & endLine).Copy
Set tmpWs = ThisWorkbook.Worksheets.Add
tmpWs.Paste
tmpWs.Select
tmpWs.Copy
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs fileName:="H:\" & fileName & " .xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ActiveWorkbook.Close
tmpWs.Delete
End With
End Sub
Something like this
This code dumps the files to single sheet csv files under a directory held by strDir, "C:temp" in this example
Sub ParseCOlumn()
Dim X
Dim strDir As String
Dim strFName As String
Dim strText As String
Dim lngRow As Long
Dim lngStart As Long
Dim objFSO As Object
Dim objFSOFile As Object
Set objFSO = CreateObject("scripting.filesystemobject")
strDir = "C:\temp"
X = Application.Transpose(Range([a1], Cells(Rows.Count, "A").End(xlUp)))
'test for first record not being "***"
lngStart = 1
If X(1) <> "***" Then
strFName = X(1)
lngStart = 2
End If
For lngRow = lngStart To UBound(X)
If X(lngRow) <> "***" Then
If Len(strText) > 0 Then
strText = strText & (vbNewLine & X(lngRow))
Else
strText = X(lngRow)
End If
Else
Set objFSOFile = objFSO.createtextfile(strDir & "\" & strFName & ".csv")
objFSOFile.write strText
objFSOFile.Close
strFName = X(lngRow + 1)
lngRow = lngRow + 1
strText = vbNullString
End If
Next
'dump last record
If X(UBound(X)) <> "***" Then
Set objFSOFile = objFSO.createtextfile(strDir & "\" & strFName & ".csv")
objFSOFile.write strText
End If
objFSOFile.Close
End Sub

EXCEL VBA code to export to text file only works if breakpoint set

I have some code to export data from a spreadsheet to a comma delimeted file. If I have a breakpoint set anywhere in the code, the data is exported to the file as expected. If I do not have a breakpoint, the file is created without any data. Thinking this was a timing issue, I experimented with a wait cycle within the code, but this did not solve the issue. Here is the code:
Private Sub WriteDataToFile()
Dim i As Long
Dim iLastRow As Integer
Dim strFile As String
Dim FSO As FileSystemObject
Dim FSOFile As TextStream
Dim strData As String
Dim s As String
strFile = "C:\Temp\DSGELIG.txt"
' Delete the file if it already exists
DeleteFile (strFile)
' Determine the last row
iLastRow = 50
For i = 2 To 65000
strData = Range("B" + CStr(i))
If Len(strData) < 1 Then
iLastRow = i - 1
Exit For
End If
Next i
' Create the file system object
Set FSO = New FileSystemObject
Set FSOFile = FSO.OpenTextFile(strFile, ForWriting, True)
For i = 2 To iLastRow
strData = ""
With Worksheets(1)
'Debug.Print Range("B" + CStr(i))
strData = """"
' Patient Name
strData = strData + Range("B" + CStr(i))
strData = strData + """" + "," + """"
' SSN / Policy #
strData = strData + Range("C" + CStr(i))
strData = strData + """" + "," + """"
' Birthdate
strData = strData + CStr(Range("D" + CStr(i)))
strData = strData + """" + "," + """"
' Admit Date
strData = strData + CStr(Range("E" + CStr(i)))
strData = strData + """" + "," + """"
' Admit Date - 2
strData = strData + CStr(Range("F" + CStr(i)))
strData = strData + """" + "," + """"
' Account Number
strData = strData + CStr(Range("G" + CStr(i)))
strData = strData + """" + "," + """"
' Insurance Code
strData = strData + Range("H" + CStr(i))
strData = strData + """" + "," + """"
' Financial Class
strData = strData + Range("I" + CStr(i))
strData = strData + """" + "," + """"
' Location
strData = strData + Range("J" + CStr(i))
strData = strData + """"
' Write the record to the file
FSOFile.WriteLine (strData)
End With
Next i
FSOFile.Close
End Sub
THANK YOU IN ADVANCE - its been a while since I have done any VBA.
I reworked a bit Kittoes code, as this:
Sub Test()
Dim FSO As New FileSystemObject
Dim ts As TextStream
Dim strFile As String, strData As String
Dim iLastRow As Integer, i As Long, c As Long
strFile = "C:\Temp\DSGELIG.txt"
' Determine the last row
iLastRow = Cells(Rows.Count, 2).End(xlUp).Row
' Create the file system object
Set ts = FSO.CreateTextFile(strFile, True)
With Worksheets(1)
For i = 2 To iLastRow
strData = ""
For c = 2 To 10
strData = "'" & strData & .Cells(i, c) & "',"
Next c
' Write the record to the file without the last comma
ts.WriteLine Left(strData, Len(strData) - 1)
Next i
End With
ts.Close
Set ts = Nothing
Set FSO = Nothing
End Sub
I must say that I have never used FSO.CreateFile and the rest. I usually use the old Print #1 syntax. I generally try to avoid any additional reference if I can.
Updated with how I might do this from scratch:
Option Explicit
Sub Test()
Dim FSO As New FileSystemObject
Dim ts As TextStream
Dim WS As Worksheet
Dim arrData(9) As String
Dim strFile As String, strData As String
Dim iLastRow As Integer, i As Integer, j As Integer
strFile = "C:\Temp\DSGELIG.txt"
Set ts = FSO.CreateTextFile(strFile, True)
Set WS = ThisWorkbook.Worksheets(1)
iLastRow = WS.UsedRange.SpecialCells(xlCellTypeLastCell).Row
With WS
For i = 2 To iLastRow
For j = 2 To 10
arrData(j - 2) = """" & CStr(.Cells(i, j)) & """"
Next j
strData = Join(arrData, ",")
ts.WriteLine Left(strData, Len(strData) - 1)
Next i
End With
ts.Close
Set ts = Nothing
Set FSO = Nothing
End Sub
There's no need for your code that deletes the file because you can simply set overwrite to true in CreateTextFile().
I have tested this and am not running into any issues with the file getting written. I even tried to create a set of data that might be comparable to yours based off of your original export and it works just fine.

Resources