I am working on a save to pdf export from a loop function. I have set the file_name as:
Sub AutoFill_export2pdf()
'
Dim rowCount As Integer
Dim CurBU As String
Dim CurOPRID As String
Dim CurName As String
Dim CurJournalID As String
Dim CurJournalDate As String
Dim FILE_NAME As String
Sheets("List").Select
rowCount = ActiveSheet.UsedRange.Rows.count
Set Destsh = ActiveWorkbook.Sheets("Sheet")
For sourceRow = 2 To rowCount
CurOPRID = Range("A" & CStr(sourceRow)) 'OPRID
CurName = Range("B" & CStr(sourceRow)) 'Name
CurBU = Range("C" & CStr(sourceRow)) 'BU
CurJournalID = Range("D" & CStr(sourceRow)) 'Journal ID
CurJournalDate = Range("E" & CStr(sourceRow)) 'Journal Date
FILE_NAME = ActiveWorkbook.Path & "\" & "OTGL_" & "JRNL_" & CurBU & "_" & CurJournalID & "_" & Format(CurJournalDate, "mm-dd-yyyy") & "_" & ".PDF"
CurName = "*" & CurName & "*"
CurBU = "*" & CurBU & "*"
CurJournalID = "*" & CurJournalID & "*"
CurJournalDate = "*" & CurJournalDate & "*"
Destsh.Range("K27") = CurName
Destsh.Range("D7") = CurBU
Destsh.Range("G7") = CurJournalID
Destsh.Range("I7") = CurJournalDate
On Error GoTo 0
Call SaveAsPDF(Destsh, FILE_NAME)
Sheets("List").Select
Next
End Sub
Public Sub SaveAsPDF(ByVal destSheet As Worksheet, ByVal PDFName As String)
On Error Resume Next
Kill PDFName
destSheet.Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:=FILE_NAME, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub
Sub Autofill()
'
Dim rowCount As Integer
Dim CurBU As String
Dim CurName As String
Dim CurOPRID As String
Dim CurJournalID As String
Dim CurJournalDate As String
Dim FILE_NAME As String
CurName = "*" & CurName & "*"
CurBU = "*" & CurBU & "*"
CurJournalID = "*" & CurJournalID & "*"
CurJournalDate = "*" & CurJournalDate & "*"
Sheets("List").Select
rowCount = ActiveSheet.UsedRange.Rows.count
Set Destsh = ActiveWorkbook.Sheets("Sheet")
For sourceRow = 2 To rowCount
CurOPRID = Range("A" & CStr(sourceRow)) 'OPRID
CurName = Range("B" & CStr(sourceRow)) 'Name
CurBU = Range("C" & CStr(sourceRow)) 'BU
CurJournalID = Range("D" & CStr(sourceRow)) 'Journal ID
CurJournalDate = Range("E" & CStr(sourceRow)) 'Journal Date
FILE_NAME = ActiveWorkbook.Path & "\" & "OTGL_" & "JRNL_" & CurBU & "_" & CurJournalID & "_" & Format(CurJournalDate, "mm-dd-yyyy") & "_" & ".PDF"
Destsh.Range("K27") = CurName
Destsh.Range("D7") = CurBU
Destsh.Range("G7") = CurJournalID
Destsh.Range("I7") = CurJournalDate
On Error GoTo 0
Call SaveAsPDF(Destsh, FILE_NAME)
Sheets("List").Select
Next
End Sub
The goal is to export to a specific folder with the naming convention I have established. If you need the entire macro, please let me know.
In the interest of teaching to fish vs handing out fish...
Put option explicit at the very top (even before your first sub).
Open your locals window (View in the VBE). Step through your code with F8, watching your variables in the locals window to ensure that they are what you expect them to be at that step in your script.
Option explicit will identify numberous variables that you haven't
declared. ("Variable not defined")
Fix those and any other issues that come up. (When it goes to other subs it will ID issues with variables there also.)
Your issue might go away just fixing what option explicit identifies and/or it might become apparent stepping through your code and watching the locals window each time you hit F8.
If you are still stuck, then edit your post with your updated code and explain any error message and line it is occurring on. If there isn't an error explain the expected and actual behavior.
The above code works perfectly, the file I was working off of was a copy with an identical name saved in the temp folder, so all the files were saving into the active workbook path..which wasnt in the folder I was monitoring. I have about 30000 pdfs in there now from running the macro so many times, lol! Thanks to all who tried to help.
Related
Need to convert excel data into XML format.
'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
Kindly let me how to do this in VBA or provide a link where I can refer. Thanks in Advance.
For a simple case one way would be to build the xml line by line
Sub vba_code_to_convert_excel_to_xml2()
Const FOLDER = "C:\temp\"
Const XLS_FILE = "testwb.xlsx"
Const XML_FILE = "testX.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-Information ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, ar, s As String
Dim iLastRow As Long, r As Long, n As Integer
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
' create XML document
'<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
' <Name>Aravind</Name>
' <UserGroupLink UserGroupID="Sports"/>
'</User>
s = XML
For r = 2 To iLastRow
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""" & ws.Cells(r, 2) & """" & _
" EMail=""" & ws.Cells(r, 3) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
ar = Split(ws.Cells(r, 4), ",")
For n = LBound(ar) To UBound(ar)
s = s & " <UserGroupLink UserGroupID=""" & Trim(ar(n)) & """/>" & vbCrLf
Next
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-Information>"
' save
Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.createtextfile(FOLDER & XML_FILE)
ts.write s
ts.Close
MsgBox "Xml created to " & FOLDER & XML_FILE
End Sub
I know this code is a mess but it's been at least working with no errors for weeks. The directories of all the files in question exist.
'''
Sub NEW_PO()
'''''''''''''''''''''''''''''''''''Declare Variables''''''''''''''''''''''''''''''''''''''''''''
Dim disc As String
Dim New_Data_Column As Long 'last date ordered column (number)
Dim NewPO_num As String 'New_Data_Column - 10 (needs leading "0" for single digits)
Dim Job_Num As String '= C2
Dim Cost_Code As String '= Active sheet name
Dim lastCol As String 'last date ordered column (Letter)
Dim sht As Worksheet
Dim lastRow As Long 'last row of description column
Set sht = ActiveSheet
''''''''''''''''''''''Find last row and column(letter)''''''''''''''''''''''''''''''''''''''''''
New_Data_Column = Cells(8, Columns.count).End(xlToLeft).Column
lastCol = Split(Columns(Range("A8").End(xlToRight).Column).Address(, False), ":")(1)
lastRow = sht.Cells(sht.Rows.count, 3).End(xlUp).Row
'''''''''''''''''''''''''''''Check for Data'''''''''''''''''''''''''''''''''''''''''''''''''''''
If WorksheetFunction.CountA(Range(lastCol & "11:" & lastCol & lastRow)) = 0 Then
MsgBox "Error! Please enter data to continue."
Exit Sub
ElseIf WorksheetFunction.CountA(Range(lastCol & "10")) = 0 Then
MsgBox "Error! Please enter date to continue."
Range(lastCol & "10").Select
Exit Sub
Else
''''''''''''''''''''''''''''''''Propmt for description of PO''''''''''''''''''''''''''''''''''''
disc = InputBox("Please enter a description for this Purchase Order.", "New Purchase Order")
If disc = "" Then
MsgBox "You Must Enter A Description!"
Exit Sub
End If
''''''''''''''''''''''''''''''''''Set Cost Code''''''''''''''''''''''''''''''''''''''''''''''''
Cost_Code = sht.name
'''''''''''''''''''''''''''''''''Set Job Number''''''''''''''''''''''''''''''''''''''''''''''''
Job_Num = sht.Cells(2, 4).Text 'as text to keep formatting
'''''''''''''''''''''''''''''Set New Purchase Order Number'''''''''''''''''''''''''''''''''''''
sht.Range("A4").Value = sht.Range("A4").Value + 1
If sht.Range("A4").Value < 10 Then
NewPO_num = "0" & sht.Range("A4").Value
Else
NewPO_num = sht.Range("A4").Value
End If
''''''''''''Open PO Template and save as PO number & Copy PO to S/R Log''''''''''''''''''''
Dim sPath As String
sPath = Application.ThisWorkbook.path
Dim i As Integer
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet
Dim lastPO_row As Long
Dim lastSR_row As Long
Dim wkb3 As Workbook
Dim sht3 As Worksheet
Dim sht4 As Worksheet
Application.ScreenUpdating = False
Set wkb1 = ThisWorkbook
Set wkb2 = Workbooks.Open(sPath & "\1 CONSTRUCTION\Purchase Orders\Purchase Order Template.xlsm")
Set wkb3 = Workbooks.Open(sPath & "\1 CONSTRUCTION\RECEIVED MATERIALS\SR Log.xlsx")
Set sht1 = wkb1.Sheets(Cost_Code)
Set sht2 = wkb2.Sheets("Sheet1")
Set sht3 = wkb3.Sheets("Sheet1")
Set sht4 = wkb2.Sheets("Job Addresses")
'''
This is where the error is occurring. Normally it would save the template as specified with no problems. I have deleted the code and written it in notepad and pasted it back into excel and it still gives an error. I've tried on multiple computers with the same result. I even uninstalled and reinstalled office and still not working.
'''
wkb2.SaveAs (sPath & "\1 CONSTRUCTION\Purchase Orders\" & Cost_Code & "\" & Job_Num & "-" & NewPO_num
& "-" & Cost_Code & " " & disc & ".xlsm")
wkb3.SaveAs (sPath & "\1 CONSTRUCTION\RECEIVED MATERIALS\" & Cost_Code & "\" & Job_Num & "-" &
NewPO_num & "-" & Cost_Code & " " & disc & ".xlsx")
sht2.name = Job_Num & "-" & NewPO_num & "-" & Cost_Code & " " & disc
lastPO_row = sht2.Cells(sht.Rows.count, 3).End(xlUp).Row + 1
lastSR_row = sht3.Cells(sht.Rows.count, 1).End(xlUp).Row + 1
''''''''''''Copy relevant entries to PO sheet and Shipping/Receiving Log'''''''''''''''''''
For i = 11 To lastRow
If sht1.Cells(i, New_Data_Column).Value <> "" Then
sht1.Range(lastCol & i).Copy
sht2.Range("A" & lastPO_row).PasteSpecial xlPasteValues
sht3.Range("D" & lastSR_row).PasteSpecial xlPasteValues
sht1.Range("B" & i & ":C" & i).Copy
sht2.Range("B" & lastPO_row & ":C" & lastPO_row).PasteSpecial xlPasteValues
sht3.Range("A" & lastSR_row & ":B" & lastSR_row).PasteSpecial xlPasteValues
lastPO_row = lastPO_row + 1
lastSR_row = lastSR_row + 1
End If
Next
sht2.Range("E6").Value = wkb1.Sheets("PM Dashboard").Range("O3").Value
sht2.Range("E7").Value = Job_Num & "-" & NewPO_num & "-" & Cost_Code
sht2.Range("E8").Value = Dashboard.Sheets("PM Dashboard").Range("Y2").Value
'add this job's address to list of addresses on PO
sht4.Range("A7").Value = wkb1.Sheets("PM Dashboard").Range("O3").Value & vbNewLine _
& wkb1.Sheets("PM Dashboard").Range("AP3").Value & vbNewLine & wkb1.Sheets("PM
Dashboard").Range("AP4").Value
wkb2.Save
sht3.Range("C1").Value = Job_Num & "-" & NewPO_num & "-" & Cost_Code & " " & disc
wkb3.Save
wkb3.Close
'''''''''''''''''''''copy over last column and hide previous'''''''''''''''''''''
sht1.Columns(New_Data_Column).Copy
sht1.Columns(New_Data_Column + 1).PasteSpecial Paste:=xlPasteFormats
sht1.Range(lastCol & "8:" & lastCol & "9").Copy
sht1.Range(lastCol & "8:" & lastCol & "9").Offset(0, 1).PasteSpecial Paste:=xlPasteValues
Call HIDE
wkb1.Save
Application.ScreenUpdating = True
End If
End Sub
'''
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'm working on macro for MacBook for separating codes that we paste in file.
After running codes should show up in a folder on my desktop called Tour Codes.
However, file is not getting saved and macro shows error.
I've tried multiple adjustments and changing location of file but the problem remains.
I would appreciate any suggestions.
Sub create_files()
Application.ScreenUpdating = False
Dim iName, iPath
iName = GetUserNameMac
'Get Path and Workbook Name
'iPath = ActiveWorkbook.Path
iPath = "Macintosh HD:Users:" & iName & ":Desktop:Tour Codes"
Sheets("Data").Select
...
'create files
Dim r1, ddate, gate, id, cap, firstrow, rowcount, newcode
r1 = 2
firstrow = 2
...
Application.DisplayAlerts = False
'save file
ChDir "Macintosh HD:Users:" & iName & ":Desktop:Tour Codes"
ActiveWorkbook.SaveAs Filename:= _
iPath & ":" & id & "_" & Format(ddate, "yyyy-mm-dd") & "_" & gate & "_" & firstrow & ".csv", _
FileFormat:=xlCSV, CreateBackup:=False
'ActiveWorkbook.SaveAs iPath & ":" & merchWk
'ActiveWorkbook.SaveAs iPath & "/" & merchWk
Windows("Gate 1 codes macro.xlsm").Activate
'copy rows to file
'Rows(firstrow & ":" & firstrow + rowcount - 2).Select
Range(Cells(firstrow, 1), Cells(firstrow + rowcount - 2, 1)).Select
Selection.Copy
Windows(id & "_" & Format(ddate, "yyyy-mm-dd") & "_" & gate & "_" & firstrow & ".csv").Activate
'Cells(2, 1).Select
Cells(1, 1).Select
ActiveSheet.Paste
'Columns("A:E").EntireColumn.AutoFit
Columns("A:A").EntireColumn.AutoFit
'save file
Cells(1, 1).Select
ActiveWorkbook.Save
ActiveWindow.Close
Application.DisplayAlerts = True
Windows("Gate 1 codes macro.xlsm").Activate
firstrow = r1 - 1
r1 = firstrow
Loop Until r1 > lastrow
End Sub
Function GetUserNameMac() As String
Dim sMyScript As String
sMyScript = "set userName to short user name of (system info)" & vbNewLine & "return userName"
GetUserNameMac = MacScript(sMyScript)
End Function
VBA errors out on these lines:
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