In the following code (full subroutine at the bottom) I want to save a worksheet row by row into textfiles. Row 1 has the headers, Col 1 has the filename for the row.
It works fine until I get to the execution of this line inside the For loop:
wbNew.SaveAs fileName:=strFile, FileFormat:=xlText, CreateBackup:=False
And the error I get is a run-time error "Automation error", and when I hit DEBUG, it highlights the line of code above it:
wb.ActiveSheet.Rows(r).Copy wbNew.Sheets(1).Rows(1)
As far as I can tell, that line executes correctly, so I'm confused as to why it would highlight that line.
I've used the Saveas code in other subroutines and have been successful.
Can anyone figure out what's wrong?
Thanks in advance!
Full code here:
Sub SaveRowsAsTXT()
Dim wb As Excel.Workbook, wbNew As Excel.Workbook
Dim r As Long
Dim strFolder As String
Dim strFile As String
Dim fName As String
Dim LastCol As Long
Dim LastRow As Long
strFolder = "L:\test\" 'folder where files will be saved
Application.ScreenUpdating = False
Application.DisplayAlerts = False 'will overwrite existing files without asking
ActiveWorkbook.Worksheets("Sheet1").Visible = True 'currently hidden
ActiveWorkbook.Worksheets("Sheet1").Copy
Set wb = ActiveWorkbook
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set wbNew = Workbooks.Add 'adds blank workbook
wb.Activate
For r = 2 To LastRow
fName = Cells(r, 1).Value
strFile = strFolder & fName & ".txt"
'copy row to new wkbk
wb.ActiveSheet.Rows(r).Copy wbNew.Sheets(1).Rows(1)
'save
wbNew.SaveAs fileName:=strFile, FileFormat:=xlText, CreateBackup:=False
'close
wbNew.Close
Next
ActiveWorkbook.Worksheets("Sheet1").Visible = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This is a crosspost from: http://www.mrexcel.com/forum/excel-q...blem-save.html
Bookmarks