How can I change the separator that a CSV file is exported with in VBA without changing regional settings etc?
The macro should be used across multiple computers and different users, I don't want to confuse people with changing global settings on their computers.
Is there any way to use another separator?
This is my current code, but the values are separated with commas, I want semicolons
Sub ExportToCSV()
'Variables--------------------------------------------------------------
Dim CSVFileName As String
Dim sheet As Integer
Dim WsData As Worksheet
Set WsData = Worksheets("Database")
'-----------------------------------------------------------------------
WsData.Range(WsData.Cells(7, 9), WsData.Cells(7, 2).End(xlDown)).Copy
Application.DisplayAlerts = False 'avoid "save prompt window"
' Disable screen updating to improve performance
Application.ScreenUpdating = False
Workbooks.Add
ActiveSheet.Paste
' Convert the first row to lowercase
For Each cell In Range("A1:H1")
cell.Value = LCase(cell.Value)
Next cell
CSVFileName = ThisWorkbook.Path & "\" & "Database_" & VBA.Format(VBA.Now, "dd-mm-yy") & ".csv"
ActiveSheet.SaveAs Filename:=CSVFileName, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
' Enable screen updating again
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Note: there could be commas inside the data it is copying.
Any help is greatly appreciated, thank you.
Option Explicit
Sub exportcsv()
Const SHT_NAME = "Database"
Const HDR = 7
Const DELIM = ";"
Dim wb As Workbook, ws As Worksheet, arData
Dim oFSO As Object, oFS As Object
Dim c As Long, i As Long, n As Long, iLastrow As Long
Dim CSVFilename As String, s As String, quote As String
Dim t0 As Single: t0 = Timer
' create text file
Set wb = ThisWorkbook
CSVFilename = wb.Path & "\" & "Database_" & VBA.Format(VBA.Now, "dd-mm-yy") & ".csv"
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFS = oFSO.CreateTextFile(CSVFilename, True, True) 'overwrite, Unicode
' write out lines
Set ws = wb.Sheets(SHT_NAME)
With ws
iLastrow = .Cells(Rows.count, "B").End(xlUp).Row
' copy to array
arData = .Range("B1:I1").Offset(HDR - 1).Resize(iLastrow - HDR + 1) ' col 2-9
For i = 1 To UBound(arData)
s = ""
For c = 1 To UBound(arData, 2)
' header
If i = 1 Then arData(i, c) = LCase(arData(i, c))
' add quotes if special chr in value
If arData(i, c) Like "*[;""]*" Then
quote = Chr(34) ' "
Else
quote = ""
End If
' change " to ""
arData(i, c) = Replace(arData(i, c), Chr(34), Chr(34) & Chr(34))
If c > 1 Then s = s & DELIM
s = s & quote & arData(i, c) & quote
Next
oFS.writeline s
n = n + 1
Next
End With
oFS.Close
MsgBox n & " lines written to " & CSVFilename, _
vbInformation, Format(Timer - t0, "0.0 secs")
End Sub
Related
So I managed to create a code to copy and paste listbox values to a newly created excel file.
The thing is, I have it all concatenated and separated by a comma. It works fine but because of how it is exported, then I have to use Excel text to columns functionality to put the data like I want.
Here's the code:
Private Sub button_Export_AMAT_Click()
Dim i As Integer
Dim n As Integer
Dim strLine As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("\\yvavm301\Commun\CF_GDC\base de dados a trabalhar\AM_AT.csv", True)
For i = 0 To Me.List_AM_AT.ListCount - 1
For n = 0 To Me.List_AM_AT.ColumnCount - 1
strLine = strLine & """" & Me.List_AM_AT.Column(n, i) & ""","
Next n
strLine = Left(strLine, Len(strLine) - 1)
a.writeline (strLine)
strLine = ""
Next i
MsgBox "Your file is exported"
End Sub
My question is: is it possible to export a like for like table, ie. having the same number of columns and having them populated with right values?
The change has to be made here (see below), right?
strLine = strLine & """" & Me.List_AM_AT.Column(n, i) & ""","
a.writeline (strLine)
I've tried without luck the following:
strLine = Me.List_AM_AT.Column(n, i)
a.cells(i,n).writeline (strLine)
Does anyone have an idea of what to do?
As said in my comment you could create an Excel file in your code and write the values to that file. Right now you create a text file with your code which leads to the issues you describe in your post (text assistant etc.)
Private Sub button_Export_AMAT_Click()
Dim i As Integer
Dim n As Integer
' You might need to add a reference to Excel if your host application is Access
' Extra/Reference and select Microsoft Excel Object Library
Dim xl As Excel.Application
Set xl = New Excel.Application
Dim wkb As Workbook
Set wkb = xl.Workbooks.Add
Dim wks As Worksheet
Set wks = wkb.Sheets(1)
'Dim strLine As String
'Set fs = CreateObject("Scripting.FileSystemObject")
'Set a = fs.CreateTextFile("\\yvavm301\Commun\CF_GDC\base de dados a trabalhar\AM_AT.csv", True)
For i = 0 To Me.List_AM_AT.ListCount - 1
For n = 0 To Me.List_AM_AT.ColumnCount - 1
wks.Cells(i + 1, n + 1).Value = Me.List_AM_AT.Column(n, i)
'strLine = strLine & """" & Me.List_AM_AT.Column(n, i) & ""","
Next n
'
' strLine = Left(strLine, Len(strLine) - 1)
' a.writeline (strLine)
' strLine = ""
Next i
wkb.SaveAs "D:\TMP\EXPORT.XLSX" ' Adjust accordingly
wkb.Close False
xl.Quit
MsgBox "Your file is exported"
End Sub
I inherited VBA code that has not worked since my work updated our version of Excel.
The original code looped through all Excel files in a specific folder.
If data in specific cells was blank or a 0, would rename the whole workbook so I would know what files to delete after the fact.
This is the original code. I don't need it to do all of this anymore.
This is part one:
Sub AllFilesWeekly()
Dim folderPath As String
Dim filename As String
Dim wb As Workbook
folderPath = "C:\Users\" & (Environ$("Username")) & "\Desktop\Process Production\" 'change to suit
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
filename = Dir(folderPath & "*.xlsx")
Do While filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & filename)
'Call a subroutine here to operate on the just-opened workbook
Call getmetrics
On Error Resume Next
If Not ActiveWorkbook.Name Like "Audit Hub Report Distribution*" Then
ActiveWorkbook.Close
End If
filename = Dir
Loop
Application.ScreenUpdating = True
End Sub
The second part:
Sub getmetrics()
Dim cell As Range
Dim procstring As String, wbname As String
'Dim OQAYTD As String
Dim OQAMTD As String
Dim ORLYTD As String
Dim ORLMTD As String
Dim DR As String
Dim Audits As Long
Dim permonth As String, peryear As String, permonthrl As String, peryearrl As String
Dim RS As Worksheet, AD As Worksheet, QD As Worksheet, ws As Worksheet, YN As Boolean
For Each ws In Worksheets
If ws.Name = "Audit Detail" Then
YN = True
End If
Next ws
If YN = True Then
ActiveWorkbook.Sheets(2).Name = ("Rep Summary")
Set RS = ActiveWorkbook.Sheets("Rep Summary")
Set AD = ActiveWorkbook.Sheets("Audit Detail")
Set QD = ActiveWorkbook.Sheets("Question Detail")
With Sheets("Process Summary")
For Each cell In Range(Range("A3"), Range("A9999").End(xlUp))
If cell.Value = "Record Level YTD" Then
ORLYTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "YTD Quality Average" Then
OQAYTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "Record Level Quality Average" Then
ORLMTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "Quality Average" Then
OQAMTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "Audits" Then
Audits = Range(cell.Address).Offset(0, 1).Value
End If
End If
End If
End If
End If
Next cell
End With
wbname = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)
peryear = VBA.Format(OQAYTD, "Percent")
permonth = VBA.Format(OQAMTD, "Percent")
peryearrl = VBA.Format(ORLYTD, "Percent")
permonthrl = VBA.Format(ORLMTD, "Percent")
DR = Right(Sheets("Process Summary").Range("A2").Value, Len(Sheets("Process
Summary").Range("A2").Value) - 12)
RS.Range(RS.Range("A1"), RS.Range("IV1").End(xlToLeft)).AutoFilter
RS.Range(RS.Range("A1"), RS.Range("IV1").End(xlToLeft)).EntireColumn.AutoFit
AD.Range(AD.Range("A1"), AD.Range("IV1").End(xlToLeft)).AutoFilter
AD.Range(AD.Range("A1"), AD.Range("IV1").End(xlToLeft)).EntireColumn.AutoFit
QD.Range(QD.Range("A1"), QD.Range("IV1").End(xlToLeft)).AutoFilter
QD.Range(QD.Range("A1"), QD.Range("IV1").End(xlToLeft)).EntireColumn.AutoFit
Application.DisplayAlerts = False
procstring = wbname & "|" & permonth & "|" & Audits & "|" & peryear & "|" & permonthrl & "|" &
peryearrl & "|" & DR ' & "|" & Users
Debug.Print procstring
Else
Application.DisplayAlerts = False
Dim AWN As String
AWN = ActiveWorkbook.FullName
Debug.Print "Not Audited: " & ActiveWorkbook.Name
ActiveWorkbook.SaveAs "C:\Users\" & (Environ$("Username")) & "\Desktop\Process Production\Delete -" & Second(Now)
Kill AWN
ActiveWorkbook.Close savechanges:=True
Application.DisplayAlerts = True
End If
End Sub
All I need to do is look at cell D3 on the "Process Summary" tab.
If the value in that space is "0.00%", rename the workbook to delete and loop on until all workbooks are looked at.
I do not need to screen print all the extra numbers any more.
Build a Collection of filenames that match the criteria and then use it to rename the files.
Option Explicit
Sub AllFilesWeekly()
Dim folderPath As String, filename As String
Dim wb As Workbook, ws As Worksheet
Dim col As Collection, n As Long
Set col = New Collection
folderPath = "C:\Users\" & (Environ$("Username")) & "\Desktop\Process Production\" 'change to suit
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
' scan folder
filename = Dir(folderPath & "*.xlsx")
Do While filename <> ""
Set wb = Workbooks.Open(folderPath & filename, True, True) ' update links, readonly
For Each ws In wb.Sheets
If ws.Name = "Process Summary" Then
If Format(ws.Range("D3"), "0.00%") = "0.00%" Then
col.Add wb.Name
End If
End If
Next
wb.Close
n = n + 1
filename = Dir
Loop
' result
MsgBox "Files scanned = " & n & vbCrLf & _
"To delete = " & col.Count, vbInformation, folderPath
' rename
If col.Count > 0 Then
If MsgBox("Continue to rename ?", vbYesNo) = vbYes Then
For n = 1 To col.Count
Name folderPath & col(n) As folderPath & "delete_" & col(n)
Next
MsgBox "Rename done"
End If
End If
End Sub
I have between 800 excels files that I need to transfer over to one sheet but before the transfer, I need to add a column ("A:A") and copy one cell value (before column added ("C1") after column ("D1")) and use column ("C:C") to get the range it would need to be pasted in column("A:A")
I have done the code already but struggling to add this on. If anyone can help that would be amazing.
Sub LoopThrough()
Dim MyFile As String, Str As String, MyDir As String
Dim sh As Worksheet, MasterRange As Range, TempWB As Workbook, TempSH As Worksheet, TempRng As Range, TempRow As Range
Dim NewMasterLine As Long
Dim StartTime As Double
Dim MinutesElapsed As String
StartTime = Timer
On Error GoTo ErrorHandler
Set sh = ThisWorkbook.Worksheets("Sheet1")
' Change address to suite
MyDir = "C:\"
MyFile = Dir(MyDir & "*.xls")
ChDir MyDir
' The following lines will put excel in a state similar to "frozen" mode. This will increase the code performance, as CPU will solely focus on performing
' the operations required by the code and not on showing the changes happening on excel
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim x As Long
x = 0
' Here starts the loop related to the files in folder
Do While MyFile <> ""
'TempWB is a Worksheet object - will be the importing worksheet. TempRng is the used range in sheet 1 of the workbook
Set TempWB = Workbooks.Open(FileName:=MyFile, UpdateLinks:=False, Password:=CalcPassword(MyFile))
Columns(1).Insert
Range("c2").Copy Range("A4:A10000")
Set TempSH = TempWB.Worksheets(1)
Set TempRng = TempSH.Range("A1:DB" & TempSH.Range("A" & TempSH.Rows.Count).End(xlUp).Row)
TempRng.Range("A:A").Insert ' This is where I tried to add in the extra column
TempRng.Range("A1").Value = TempRng.Range("D1").Value ' Tried doing this as a test but still pasted as if no changes had been made????
'NewMasterLine is the last used row (+1) of the Master Workbook (It is basically where the new rows will start to be imported)
NewMasterLine = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
If NewMasterLine > 1 Then NewMasterLine = NewMasterLine + 1
'This will loop through all the rows of the range to be imported, checking the first column.
' If the value in the second column is work-xne-ams, will import the single row in the master workbook
For Each TempRow In TempRng.Rows
If Left(TempRow.Cells(1, 2).Value, 5) = "SHIFT" Or TempRow.Row < 4 Then
'If TempRow.Cells(1, 2).Value = "SHIFT--1" Or TempRow.Row < 4 Then
Set MasterRange = sh.Range("A" & NewMasterLine & ":DA" & NewMasterLine)
MasterRange.Value = TempRow.Value
NewMasterLine = NewMasterLine + 1
End If
Next
TempWB.Close savechanges:=False
MyFile = Dir()
x = x + 1
ThisWorkbook.Worksheets("PWD").Range("H2") = x
Loop
ErrorHandler:
If Err.Number <> 0 Then MsgBox "An error occurred." & vbNewLine & vbNewLine & "Last file that was attempted to be opened: " & MyFile & vbNewLine & vbNewLine & Err.Description
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation
End Sub
Function CalcPassword(FileName As String) As String
CalcPassword = ""
On Error Resume Next
Dim TheFile As String: TheFile = Split(Split(FileName, "\")(UBound(Split(FileName, "\"))), ".")(0)
Dim PWD As Range: Set PWD = ThisWorkbook.Worksheets("PWD").ListObjects("PWD").DataBodyRange
CalcPassword = WorksheetFunction.VLookup(TheFile, PWD, 5, False)
End Function
I would like to say i'm an intermediate user of Excel VBA but i'm struggling with this one.
I have written a script to read a text file and strip out all the information I need and then add it to Worksheet that is named by the text file name and then todays date.
Set WS1 = ActiveWorkbook.Sheets("Home")
myFile = Application.GetOpenFilename()
myFileName = FileNameOf(myFile)
WS1.Copy After:=Sheets(Sheets.Count)
Set WS2 = ActiveSheet
strNewSheetName = myFileName & " - " & Format(Now, "DD-MM-YY")
blnSheetCheck = CheckIfSheetExists(strNewSheetName)
If blnSheetCheck = True Then
blnDeleteSheet = MsgBox("NOTICE:" & vbCrLf & vbCrLf & "This text file has already been added today!!" & vbCrLf & vbCrLf & "would you like to delete the existing one?", vbYesNo + vbCritical)
If blnDeleteSheet = vbYes Then
ActiveWorkbook.Sheets(strNewSheetName).Delete
WS2.Name = strNewSheetName
Else
' Roll the number here
End If
Else
WS2.Name = strNewSheetName
End If
I use this function to check if it exists
Function CheckIfSheetExists(SheetName) As Boolean
CheckIfSheetExists = False
Err.Clear
On Error Resume Next
Set WS99 = Sheets(SheetName)
If Err = 0 Then
CheckIfSheetExists = True
Else
CheckIfSheetExists = False
End If
End Function
When I first wrote the code I was going to add a time to the sheet name but it will sometimes push the name over the 31 character limit.
So I would like some guidance on how I can add a numeric to the end of the sheet name and then repeat the process to see if that sheet name exists and then move it up a number and then check again.
Thank you in advance
Andy
This will name the sheets as, for example:
Test 03-05-18 and then Test 03-05-18_01 up to Test 03-05-18_99.
Update this line to allow more copies:
TempShtName = SheetName & "_" & Format(lCounter, "00")
There's one procedure and two functions in the code:
The first is a copy of your code (with variables declare).
The second figures out the name of the sheet.
The third checks if the sheet exists.
Public Sub Test()
Dim WrkBk As Workbook
Dim WS1 As Worksheet, WS2 As Worksheet
Dim myFile As String
Dim myFileName As String
myFile = Application.GetOpenFilename()
'File name including extension:
'myFileName = Mid(myFile, InStrRev(myFile, "\") + 1)
'File name excluding extension:
myFileName = Mid(myFile, InStrRev(myFile, "\") + 1, InStrRev(myFile, ".") - InStrRev(myFile, "\") - 1)
With ThisWorkbook
Set WS1 = .Sheets("Home")
WS1.Copy After:=.Worksheets(.Worksheets.Count)
Set WS2 = .Worksheets(.Worksheets.Count)
WS2.Name = GetSheetName(myFileName & " - " & Format(Now, "dd-mm-yy"))
End With
End Sub
'Return a numbered sheet name (or the original if it's the first).
Public Function GetSheetName(SheetName As String, Optional WrkBk As Workbook) As String
Dim wrkSht As Worksheet
Dim TempShtName As String
Dim lCounter As Long
If WrkBk Is Nothing Then
Set WrkBk = ThisWorkbook
End If
TempShtName = SheetName
Do While WorkSheetExists(TempShtName)
lCounter = lCounter + 1
TempShtName = SheetName & "_" & Format(lCounter, "00")
Loop
GetSheetName = TempShtName
End Function
'Check if the sheet exists.
Public Function WorkSheetExists(SheetName As String, Optional WrkBk As Workbook) As Boolean
Dim wrkSht As Worksheet
If WrkBk Is Nothing Then
Set WrkBk = ThisWorkbook
End If
On Error Resume Next
Set wrkSht = WrkBk.Worksheets(SheetName)
WorkSheetExists = (Err.Number = 0)
Set wrkSht = Nothing
On Error GoTo 0
End Function
Edit:
To remove illegal characters and keep the sheet name to 31 characters you could add this code in the GetSheetName function just before the TempShtName = SheetName line:
Dim x As Long
Dim sChr As String
Const ILLEGAL_CHR As String = "\/*?:[]"
For x = 1 To Len(SheetName)
sChr = Mid(SheetName, x, 1)
If InStr(ILLEGAL_CHR, sChr) > 0 Then
SheetName = Replace(SheetName, sChr, "_")
End If
Next x
If Len(SheetName) > 28 Then
SheetName = Left(SheetName, 28)
End If
Set WS1 = ActiveWorkbook.Sheets("Home")
myFile = Application.GetOpenFilename()
myFileName = FileNameOf(myFile)
WS1.Copy After:=Sheets(Sheets.Count)
Set WS2 = ActiveSheet
strNewSheetName = myFileName & " - " & Format(Now, "DD-MM-YY")
blnSheetCheck = CheckIfSheetExists(strNewSheetName)
If blnSheetCheck = True Then
blnDeleteSheet = MsgBox("NOTICE:" & vbCrLf & vbCrLf & "This text file has already been added today!!" & vbCrLf & vbCrLf & "would you like to delete the existing one?", vbYesNo + vbCritical)
If blnDeleteSheet = vbYes Then
ActiveWorkbook.Sheets(strNewSheetName).Delete
WS2.Name = strNewSheetName
Else
'======Here's the new bit=================
Dim x as integer
x = 1
Do
strnewsheetname = left(strnewsheetname,30) & x
blnSheetCheck = CheckIfSheetExists(strNewSheetName)
x = x +1
Loop while blnSheetCheck
WS2.Name = strNewSheetName
'=============End of New Bit=============
End If
Else
WS2.Name = strNewSheetName
End If
Technically this will keep looping above 9, but from you've said I don't think this will be a problem
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