Very new to VBA and trying to create an automated textfile export.
Currently it works like a charm for row 1 and the textfile is created. But when adding data on row 2 as well I get:
Runtime error 91, Object variable or With block variable not set.
Any help would be much appreciated!
Sub Exportera()
Dim bKlar As Boolean
Dim bSkrivPSlut As Boolean
Dim bSkrivPStart As Boolean
Dim fsoExpFil As FileSystemObject
Dim fsoTextStream2 As TextStream
Dim sExportFile As String
Dim iSvar As Integer
Dim iSvar2 As Integer
Dim sSokvag As String
Dim sFilnamn As String
Dim sTemp As String
Dim sPFalt As String
Dim cVarde As Currency
Dim sDatum As String
'alright då skapar vi fil och skriver till den
Set fsoExpFil = New FileSystemObject
Range("K10").Select
sSokvag = Trim(ActiveCell.FormulaR1C1)
Range("K13").Select
sFilnamn = Trim(ActiveCell.FormulaR1C1)
If Not UCase(Right(sFilnamn, 4)) = ".TXT" Then
sFilnamn = sFilnamn & ".txt"
End If
sExportFile = sSokvag & "\" & sFilnamn
If sSokvag = "" Or sFilnamn = "" Then
MsgBox "Exporten avbryts då sökväg och filnamn saknas för exportfilen.", vbInformation, sAppName
Exit Sub
Else
If fsoExpFil.FileExists(sExportFile) = True Then
iSvar = MsgBox("Filen " & sFilnamn & " finns redan, skall den ersättas?", vbYesNo, sAppName)
If iSvar = vbNo Then
Exit Sub
End If
Else
iSvar = MsgBox("Är du säker att du vill exportera?", vbYesNo, "Exportera")
End If
End If
If iSvar = vbYes Then
Set fsoTextStream2 = fsoExpFil.OpenTextFile(sExportFile, ForWriting, True)
fsoTextStream2.WriteLine "Filhuvud"
fsoTextStream2.WriteLine vbTab & "Typ=" & """Anställda"""
sTemp = "SkapadAv=" & """"
sTemp = sTemp & "Importfil"
sTemp = sTemp & """"
fsoTextStream2.WriteLine vbTab & sTemp
fsoTextStream2.WriteLine vbTab & "DatumTid=" & "#" & Now & "#"
bKlar = False
i = 1
Sheets("Data").Select
While bKlar = False
i = i + 1
Range("A" & i).Select
If Trim(ActiveCell.FormulaR1C1) <> "" Then
If IsNumeric(ActiveCell.FormulaR1C1) Then
fsoTextStream2.WriteLine "PStart"
fsoTextStream2.WriteLine " Typ = ""Anställda"""
Range("A" & i).Select
If Trim(ActiveCell.FormulaR1C1) <> "" Then
fsoTextStream2.WriteLine " Anställningsnummer = " & ActiveCell.FormulaR1C1
End If
Range("B" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Namn=" & Trim(ActiveCell.FormulaR1C1)
End If
Range("D" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Utdelningsadress=" & ActiveCell.FormulaR1C1
End If
Range("E" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " co_adress=" & ActiveCell.FormulaR1C1
End If
Range("G" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Postadress=" & ActiveCell.FormulaR1C1
End If
Range("F" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Postnummer=" & ActiveCell.FormulaR1C1
End If
Range("C" & i).Select
If Trim(ActiveCell.Text) <> "" Then
sTemp = ActiveCell.FormulaR1C1
sTemp = Mid(sTemp, 1, 6) & "-" & Mid(sTemp, 7)
fsoTextStream2.WriteLine " Personnummer=" & sTemp
End If
Range("H" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " E_mail=" & ActiveCell.FormulaR1C1
End If
Range("I" & i).Select
If Trim(ActiveCell.Text) <> "" Then
sTemp = ActiveCell.FormulaR1C1
Range("AM" & i).Select
sTemp = sTemp & ActiveCell.FormulaR1C1
sTemp = Replace(sTemp, "-", "")
fsoTextStream2.WriteLine " Bankkontonummer=" & sTemp
End If
Range("J" & i).Select
If Trim(ActiveCell.Text) <> "" Then
sDatum = ActiveCell.Text
fsoTextStream2.WriteLine " Anställningsdatum=" & "#" & sDatum & "#"
End If
fsoTextStream2.WriteLine "PSlut"
fsoTextStream2.Close
MsgBox "Exporten är klar", vbInformation, sAppName
End If
Else
bKlar = True
End If
Wend
End If
End Sub
Your problem is not exactly what you'd be expecting.
Note that in your while loop, you close your filestream object at the end with fsoTextStream2.Close. What you'll be seeing is that it will successfully write the first line, but then close the file and then try to write to a file that is closed.
Simply moving this outside the loop (after wend) will fix your problem (Shown below).
fsoTextStream2.WriteLine "PSlut"
MsgBox "Exporten är klar", vbInformation, sAppName
End If
Else
bKlar = True
End If
Wend
fsoTextStream2.Close 'This line has been moved outside the loop
End If
End Sub
There's quite a few improvements for your code, if you alter it slightly to avoid .select calls. Also .value rather than .text might be useful if your cells have numeric input. Note that you can extract cell values without having them selected by using range("A" & i).value (or simply range("A" & i)) using worksheet("sheetname").range("A" & i) to access specific sheet cells. (cells(row, column) works just as well).
Related
My code renames folders based on what is in first column:
Dim sFolder As String
Option Explicit
Sub addPrefix()
Dim strfile As String
Dim filenum As String
Dim strOldDirName
Dim strNewDirName
strfile = Dir(sFolder)
Dim old_name, new_name As String
Dim i As Long
With ThisWorkbook.Worksheets("data")
For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
strOldDirName = sFolder & ThisWorkbook.Worksheets("data").Cells(i, 2).Value
strNewDirName = sFolder & ThisWorkbook.Worksheets("data").Cells(i, 1).Value & " " & ThisWorkbook.Worksheets("data").Cells(i, 2).Value
Name strOldDirName As strNewDirName
Next i
End With
End Sub
and then I check for duplicates on Column C (email column). If they are a duplicate I move them to their 'master' folder (which is just the first of the duplicates found). Upon this, it adds the suffix ' - MASTER' on to the folder.
Here is the code to move duplicates:
Sub moveDuplicates()
' This will find duplicates and move them into a master folder. It'll will then delete the row
Dim masterID
Dim masterPlatform
Dim objFileSystem
Dim FromPath As String
Dim ToPath As String
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Dim masterOldFolderName
Dim masterNewFolderName
Dim masterSuffix
Dim LastRow As Long, i As Long
Dim rngWhole As Range, rngSplit As Range
masterID = 0
masterPlatform = 0
masterSuffix = " - MASTER"
masterOldFolderName = ""
masterNewFolderName = ""
With ThisWorkbook.Worksheets("data")
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
Set rngWhole = .Range("C1:C" & LastRow)
.Range("E" & 1).Value = rngWhole
For i = 1 To LastRow
If WorksheetFunction.CountIf(rngWhole, .Range("C" & i).Value) > 1 Then
Set rngSplit = .Range("C1:C" & i)
If WorksheetFunction.CountIf(rngSplit, .Range("C" & i).Value) = 1 Then
masterID = .Range("B" & i).Value
masterPlatform = .Range("A" & i).Value
'' Renme master folders with subfix of "- MASTER"
masterOldFolderName = sFolder & masterPlatform & " " & masterID
masterNewFolderName = sFolder & masterPlatform & " " & masterID & masterSuffix
Name masterOldFolderName As masterNewFolderName
'' End of renaming
'.Range("D" & i).Value = "MASTER " & masterID
Else
'.Range("D" & i).Value = "CHILD " & masterID & " This folder: " & .Range("B" & i).Value
'MOVING FOLDER
FromPath = sFolder & .Range("A" & i).Value & " " & .Range("B" & i).Value '<< Change
ToPath = sFolder & masterPlatform & " " & masterID & masterSuffix & "\" '<< needs the slash to go into the folder
.Range("H" & i).Value = "From: " & FromPath
.Range("I" & i).Value = "From: " & ToPath
'Check if source and target folder exists
If objFileSystem.FolderExists(FromPath) = True And objFileSystem.FolderExists(ToPath) = True Then
objFileSystem.MoveFolder Source:=FromPath, Destination:=ToPath
lblStatus.Caption = "Moving " & FromPath & " To " & ToPath
Rows(i).EntireRow.Delete
lblStatus.Caption = " Deleting " & .Range("A" & i).Value & " " & .Range("B" & i).Value
'MsgBox "Source folder has moved to target folder"
Else
'MsgBox "Either source or target folder does not exist"
End If
' END OF MOVING FOLDER
' ROW GETS DELETED
End If
'.Range("C" & i).Interior.ColorIndex = 3
End If
Next i
End With
End Sub
My script works to a certain degree:
But it just puts everything into the first 'MASTER' folder
Here is my sheet:
I then call this from a button:
' Open the select folder prompt
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then ' if OK is pressed
sFolder = .SelectedItems(1) & "\"
End If
End With
If sFolder <> "" Then ' if a file was chosen
Me.txtFolderPath.Text = sFolder
'' calls functions
addPrefix
moveDuplicates
Sheet_SaveAs ' saves output
end sub
Is the reason it is not performing as expected due to I am calling it wrongly?
Full code: https://www.dropbox.com/s/k06b5hydc4v7bpn/so-files.zip?dl=0
(code can be run from developer> forms> userform1)
DEBUGGING:
I think the problem seems to arise here when debugging:
'' Renme master folders with subfix of "- MASTER"
masterOldFolderName = sFolder & masterPlatform & " " & masterID
masterNewFolderName = sFolder & masterPlatform & " " & masterID & masterSuffix
Name masterOldFolderName As masterNewFolderName
'' End of renaming
I am not sure if this is because it is in the wrong place (which I assume)
I am trying to retrieve the attributes for roughly 500 CAGE codes from the DLA and record them in my spreadsheet. I've been able to get it to work for one iteration, but, on second iteration, get the error "method navigate of object iwebbrowser2 failed"
Note the code doesn't work unless you've already opened the website before and haven't closed the browser (you need to accept the terms and conditions).
The cell B2 = https://cage.dla.mil/Search/Results?q=07187&page=1
The cell B3 = https://cage.dla.mil/Search/Results?q=00198&page=1
Sub NSCM2()
'Initialize
Dim IE As Object
Dim CAGE As String
Dim rowNeeded As String
Dim i As Integer
Dim sDD0 As String
Dim sDD1 As String
Dim sDD2 As String
Dim sDD3 As String
Dim sDD4 As String
Dim Doc As HTMLDocument
'Create IE Object
Set IE = CreateObject("INTERNETEXPLORER.APPLICATION")
'Loop for All Codes
For i = 1 To 10
'Retrieve CAGE Code
rowNeeded = CStr(i + 1)
CAGE = Range("B" & rowNeeded).Value
'Navigate to Cage Code general Page
IE.navigate CAGE
'Wait
Do
DoEvents
Loop Until IE.readyState = 4
Application.Wait (Now + TimeValue("0:00:03"))
'Follow link to details page
For Each ele In IE.document.getElementsByTagName("a")
If InStr(ele.innerText, "Details") > 0 Then ele.Click
Next
'Wait
Do
DoEvents
Loop Until IE.readyState = 4
Application.Wait (Now + TimeValue("0:00:03"))
'Pull needed values
Set Doc = IE.document
sDD0 = Doc.getElementsByTagName("span")(11).innerText
sDD1 = Doc.getElementsByTagName("span")(15).innerText
sDD2 = Doc.getElementsByTagName("span")(17).innerText
sDD3 = Doc.getElementsByTagName("span")(19).innerText
sDD4 = Doc.getElementsByTagName("span")(20).innerText
'Close IE
IE.Quit
'Insert URL
Range("F" & rowNeeded) = sDD0
'Insert Address, comma separated
If sDD1 = "" And sDD2 = "" And sDD3 = "" Then
Range("G" & rowNeeded) = sDD4
ElseIf sDD1 = "" And sDD2 = "" Then
Range("G" & rowNeeded) = sDD3 & ", " & sDD4
ElseIf sDD1 = "" And sDD3 = "" Then
Range("G" & rowNeeded) = sDD2 & ", " & sDD4
ElseIf sDD1 = "" Then
Range("G" & rowNeeded) = sDD2 & "," & sDD3 & ", " & sDD4
Else
Range("G" & rowNeeded) = sDD1 & ", " & sDD2 & ", " & sDD3 & ", " & sDD4
End If
'Insert Address Check
Range("H" & rowNeeded) = sDD1 & ";" & sDD2 & ";" & sDD3 & ";" & sDD4
Next i
End Sub
The first time through the loop, you call
IE.Quit
so your loop will fail on the second iteration
I have code below for a print function created in VBA. When I select "Return from leave" under the drop down "Type of Change", my print macro prints as a "salary" change type, not "return from leave". I cant see where I went wrong in my code or what is causing the issue... Any thoughts? Thanks in advance!
Sub pcf_print()
Dim ws As Worksheet
Dim datasheet As Worksheet
Dim fs As Object
Dim str As String
Dim bool As Boolean
If Len(ActiveSheet.Name) < 3 Then
MsgBox "This worksheet is not a PCF"
Exit Sub
End If
If Left(ActiveSheet.Name, 3) <> "PCF" Then
MsgBox "This worksheet is not a PCF"
Exit Sub
End If
'MsgBox Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v")) 'Right(ActiveSheet.Name, 4)
If InStr(ActiveSheet.Name, " vv") Then
If (CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " vv") - 1)) >= 1.2 And (ActiveSheet.Range("F10") = "(select)" Or ActiveSheet.Range("F10") = "" Or ActiveSheet.Range("F10") = "(sélect.)")) Then
MsgBox "This form has not been completed"
Exit Sub
End If
Else
If (CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v"))) < 1.2 And (ActiveSheet.Range("F9") = "(select)" Or ActiveSheet.Range("F9") = "")) Or (CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v"))) >= 1.2 And (ActiveSheet.Range("F10") = "(select)" Or ActiveSheet.Range("F10") = "" Or ActiveSheet.Range("F10") = "(sélect.)")) Then
MsgBox "This form has not been completed"
Exit Sub
End If
End If
Set datasheet = ActiveSheet
If ActiveWorkbook.Worksheets("Form Lists").Range("CorpOrStore") = "Corp" Then
str = "Corporate"
Else
str = "Stores"
End If
Set fs = CreateObject("Scripting.FileSystemObject")
bool = fs.FolderExists("H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\")
If Not bool Then
MkDir "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\"
End If
If InStr(ActiveSheet.Name, " vv") Then
If CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " vv") - 1)) >= 1.2 Then
ActiveWorkbook.SaveAs "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\" & Replace(datasheet.Range("F10"), "/", "_") & " for " & datasheet.Range("J17") & ", " & datasheet.Range("F17") & " effective " & Month(datasheet.Range("F12")) & "-" & Day(datasheet.Range("F12")) & "-" & Year(datasheet.Range("F12")) & ".xls"
End If
Else
If CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v"))) >= 1.2 Then
ActiveWorkbook.SaveAs "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\" & Replace(datasheet.Range("F10"), "/", "_") & " for " & datasheet.Range("J17") & ", " & datasheet.Range("F17") & " effective " & Month(datasheet.Range("F12")) & "-" & Day(datasheet.Range("F12")) & "-" & Year(datasheet.Range("F12")) & ".xls"
Else
ActiveWorkbook.SaveAs "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\" & datasheet.Range("F9") & " for " & datasheet.Range("J16") & ", " & datasheet.Range("F16") & " effective " & Month(datasheet.Range("F11")) & "-" & Day(datasheet.Range("F11")) & "-" & Year(datasheet.Range("F11")) & ".xls"
End If
End If
Set ws = ActiveWorkbook.Worksheets("Payroll Forms")
If Right(ActiveSheet.Name, 5) = "v1.20" Then
ActiveWorkbook.Worksheets("Form Lists").Unprotect "0nl1n3"
ActiveWorkbook.Worksheets("Form Lists").Range("B8") = "A1:G76"
ActiveWorkbook.Worksheets("Form Lists").Range("B9") = "A80:G157"
ActiveWorkbook.Worksheets("Form Lists").Range("B10") = "A160:G225"
ActiveWorkbook.Worksheets("Form Lists").Range("B11") = "A228:G259"
ActiveWorkbook.Worksheets("Form Lists").Range("B12") = "A228:G259"
ActiveWorkbook.Worksheets("Form Lists").Range("B13") = "A228:G259"
ActiveWorkbook.Worksheets("Form Lists").Range("B14") = "A263:G338"
ActiveWorkbook.Worksheets("Form Lists").Range("B15") = "A263:G338"
ActiveWorkbook.Worksheets("Form Lists").Range("B16") = "A343:G367"
ActiveWorkbook.Worksheets("Form Lists").Range("B17") = "A263:G338"
ActiveWorkbook.Worksheets("Form Lists").Range("B18") = "A160:G225"
ActiveWorkbook.Worksheets("Form Lists").Range("B19") = "A370:G420"
ActiveWorkbook.Worksheets("Form Lists").Protect "0nl1n3"
End If
If Right(ActiveSheet.Name, 5) = "v1.20" Or Right(ActiveSheet.Name, 5) = "v1.21" Or str = "Corporate" Then
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("H2")
Else
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
End If
ActiveWorkbook.Unprotect "0nl1n3"
ws.Visible = xlSheetVisible
ws.PrintOut
ws.Visible = xlSheetHidden
ActiveWorkbook.Protect "0nl1n3"
ActiveWorkbook.Close False
End Sub
OP says:
When I select "Return from leave" under the drop down "Type of Change", my print macro prints as a "salary" change type, not "return from leave"
Assuming that the
"salary" change type
corresponds to the "default print" i.e.:
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
It seems that the reason the code provided always prints the default range, it's because the lines that determine the printed output are validating the ActiveSheet.Name instead of the value in the "Type of Change field and print"
Solution proposed:
Change these lines to reflect the cell where the "Type of Change field and print" is located:
Replace ActiveSheet.Name with the corresponding cell.address i.e.: F10 and update as required the comparisons against "v1.20" and "v1.21"
If Right(ActiveSheet.Name, 5) = "v1.20" _
Or Right(ActiveSheet.Name, 5) = "v1.21" _
Or str = "Corporate" Then
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("H2")
Else
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
End If
It should become (comparison values shown as a reference, they should be updated in line with the choices in the drop-down list) :
If ActiveSheet.Range("F10").Value2 = "Return from leave" _
Or str = "Corporate" Then
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("H2")
Else
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
End If
Note:
1. Avoid using ActiveWorkbook and ActiveSheet, suggest to replace all instances of them by: ThisWorkbook and datasheet respectively.
2. Additionally, I would suggest to review and incorporate the use of With statement and Select Case statement throughout your procedure.
firstly i want to write a macro for going through of every row so if valuse of item is more than 10 creat a folder base on values of that rows.in addition without a duplicate folder !
for example if there is item20 then create a folder with this name 20_NT25153_29.9 then another rows
i wanna to add this sentence ,i know my code is very simple but i am new in VBA hence need more help :)
Sub loopthrough()
With Worksheets("Output_" & Date)
fName5 = .Range("d").Value
fName1 = .Range("B").Value
fName2 = .Range("c").Value
fName4 = "_"
BrowseForFolder = CurDir()
End With
For Each cell In ActiveWorkbook.Worksheets
If cell.Range("B").Value > "10" Then
BrowseForFolder1 = BrowseForFolder & "\" & fName1 & fName2 & fName5
MkDir BrowseForFolder1
End If
Next cell
End Sub
You could use this code:
Sub Macro1()
Dim lLastRow As Long
Dim sPath As String, sNewFolder As String
sPath = CurDir()
lLastRow = Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lLastRow
If Range("B" & i).Value > 10 Then
sNewFolder = Range("B" & i).Value & "_" & Range("C" & i).Value & "_" & Range("D" & i).Value
If Dir(sPath & "\" & sNewFolder, vbDirectory) = "" Then
MkDir (sPath & "\" & sNewFolder)
End If
End If
sNewFolder = vbNullString
Next
End Sub
Fisrt of all I check for the last row index based on A column, not to loop through whole worksheet.
In a loop I've used a Dir() function with vbDirectory parameter which returns empty string when folder does not exists & in that case it creates a folder.
Is this what you're after?
Folder name is column B value _ column C value _ column D value ?
Sub loopthrough()
Dim cell As Range, fName4
BrowseForFolder = CurDir()
fName4 = "_"
With Worksheets("Output_" & Date)
For Each cell In .Range("B1", .Range("B" & Rows.Count).End(xlUp))
If cell.Value > 10 Then
BrowseForFolder1 = BrowseForFolder & "\" & cell.Value & fName4 & cell.Offset(, 1).Value & fName4 & cell.Offset(, 2).Value
MkDir BrowseForFolder1
End If
Next cell
End With
End Sub
it works for somebody need same as me
Sub Macro1()
Dim lLastRow As Long
Dim sPath As String, sNewFolder As String
sPath = CurDir()
lLastRow = workbooks(sFilename).Sheets(1).Range("A:A").SpecialCells(xlCellTypeLastCell).Row
Workbooks(sFilename).Sheets(1).Activate
For i = 2 To lLastRow
If Workbooks(sFilename).Sheets(1).Cells(i, 2).Value >= 10 Then
sNewFolder = ActiveSheet.Range("B" & i).Value & "_" & ActiveSheet.Range("C" &
i ).Value & "_" & ActiveSheet.Range("D" & i).Value
If Dir(sPath & "\" & sNewFolder, vbDirectory) = "" Then
MkDir (sPath & "\" & sNewFolder)
End If
End If
sNewFolder = vbNullString
Next
End Sub
Good day everyone,
I have this macro, which exports all cells with formulas, BUT with blank outputs.
I only want the cells displaying as non blank to export. Any ideas?
Sub Export_A()
Dim sPath As String
Dim SFile As String
Dim nLog As Integer
sPath = "C:\AAAWork\"
SFile = sPath & ActiveSheet.Range("P9") & ".txt"
nfile = FreeFile
Open SFile For Output As #nfile
For i = 1 To ActiveSheet.UsedRange.Rows.Count
Set ThisCell = ActiveSheet.Range("A" & i)
If ThisCell.Text <> "" Then
' sInDate = ThisCell.Text
'sOutDate = Format(ThisCell.Value, "mm/yyyy")
sOutDate = Format(ThisCell.Value, "yyyy-mm")
'stemp = """" & sOutDate & """" this gives the date the " in the
beginning and end
stemp = "" & sOutDate & ""
For j = 1 To 10
If j = 1 Or j = 2 Or j = 9 Then
stemp = stemp & ";" & ThisCell.Offset(0, j)
Else
'stemp = stemp & "," & """" & ThisCell.Offset(0, j) & """" This
gives every value a " beginning and end
stemp = stemp & ";" & ThisCell.Offset(0, j)
End If
Next
End If
Print #nfile, stemp
Next
Close #nfile
MsgBox ("Completed a file called " & SFile & " has been generated")
End Sub
This is an interesting way of exporting to CSV, but it was inherited and does everything else very well.
Try placing the Write line at the end of the For loop
Sub Export_A()
Dim sPath As String
Dim SFile As String
Dim nLog As Integer
sPath = "C:\AAAWork\"
SFile = sPath & ActiveSheet.Range("P9") & ".txt"
nfile = FreeFile
Open SFile For Output As #nfile
For i = 1 To ActiveSheet.UsedRange.Rows.Count
Set ThisCell = ActiveSheet.Range("A" & i)
If ThisCell.Text <> "" Then
' sInDate = ThisCell.Text
'sOutDate = Format(ThisCell.Value, "mm/yyyy")
sOutDate = Format(ThisCell.Value, "yyyy-mm")
'stemp = """" & sOutDate & """" this gives the date the " in the beginning and end
stemp = "" & sOutDate & ""
For j = 1 To 10
stemp = stemp & ";" & ThisCell.Offset(0, j)
Next
Print #nfile, stemp
End If
Next
Close #nfile
MsgBox ("Completed a file called " & SFile & " has been generated")
End Sub
first you don't need this if statement as the output is the same if it's true or false
If j = 1 Or j = 2 Or j = 9 Then
stemp = stemp & ";" & ThisCell.Offset(0, j)
Else
'stemp = stemp & "," & """" & ThisCell.Offset(0, j) & """" This gives every value a " beginning and end
stemp = stemp & ";" & ThisCell.Offset(0, j)
End If
If the blanks are in the following columns you could change to code to:
If ThisCell.Offset(0, j) <> "" Then
stemp = stemp & ";" & ThisCell.Offset(0, j)
End If
Which will skip blank columns