Loop through variable to create folders - excel

I tried using the code below to loop through the strDir variable to create 4 different folders in 4 different locations.
It does not create the folders. No errors appear.
Dim i as Integer
JobName = NewJob.Value
If New_Job.JobYes.Value Then
strDir1 = "C:\QTR\" & JobName & " QTR"
strDir2 = "C:\QT\" & JobName & " QT"
strDir3 = "C:\EMAILS\" & JobName & " EMAILS"
strDir4 = "C:\DOCUMENTS\" & JobName & " DOCS"
For i = 1 To 4
If Dir(strDir, vbDirectory) = "" Then
MkDir strDir & i
Else
MsgBox "Directory exists."
End If
Next i
Else
End If

I agree with the array approach but avoid creating blank entries in the array. It has a zero-based index (by default) and strDir(4) actually creates 5 entries; e.g. 0, 1, 2, 3, 4.
First off, either put Option Explicit at the top of the code sheet or go into the VBE's Tools ► Options ► Editor and put a check beside Require Variable Declaration. This will quickly identify the use of undeclared variables like the strDir in your code.
Dim d As Long, strDir As Variant, JobName As String
strDir = Array("C:\QTR\" & JobName & " QTR", _
"C:\QT\" & JobName & " QT", _
"C:\EMAILS\" & JobName & " EMAILS", _
"C:\DOCUMENTS\" & JobName & " DOCS")
For d = LBound(strDir) To UBound(strDir)
If Dir(strDir(d), vbDirectory) = "" Then
MkDir strDir(d)
Else
Debug.Print strDir(d) & " exists."
End If
Next d
The LBound and
UBound functions return the Upper and Lower Boundaries of the array.

Try this code:
Dim i as Integer
Dim strDir(4) as String
JobName = NewJob.Value
If New_Job.JobYes.Value Then
strDir(1) = "C:\QTR\" & JobName & " QTR"
strDir(2) = "C:\QT\" & JobName & " QT"
strDir(3) = "C:\EMAILS\" & JobName & " EMAILS"
strDir(4) = "C:\DOCUMENTS\" & JobName & " DOCS"
For i = 1 To 4
If Dir(strDir(i), vbDirectory) = "" Then
MkDir strDir(i)
Else
MsgBox "Directory exists."
End If
Next i
Else
End If

That will indeed give an error, since its not possible to concatenate the "strDir" & i together, to use that specific parameter. Easiest way to solve this correctly is to skip the loop and use:
If Dir(strDir, vbDirectory) = "" Then
MkDir strDir1
MkDir strDir2
MkDir strDir3
MkDir strDir4
Else
MsgBox "Directory exists."
End If
If you really need to create an enormous amount of directories, lets say > 10, then you might want to use dynamically requesting parameters by name, but if you don't need it, I would not recommend it.

Related

How do I add a network path to a name in excel name manager

I have code that works to add a path to a name in the name manager, but only for local paths. When I try to use a network path, the name manager adds a colon before the first single backslash, which keeps the path from working. I have added code to debug, to remove colons, which it seems wasn't necessary. The File open dialog does return the correct path. VBA writes it like this with debug.print:
`="\\win10box3\business\... ..." `
When excel stores it in the name manager it stores it like this
`="\\Win10Box3:\Business\... ..." `
I wrote code to remove the colon before adding the name, but I'm finding the path debug.prints correct before it is stored in the Name Manager, even before the loop to remove the colon.
The only solution I have found is to manually edit the path in the name manager to remove the colon
Sub GetPath()
Debug.Print "Start GetPath routine"
'This sub gets the path to a File defined by the user within the routine
'It then calls another sub that applies that path to a name in the worksheet.
' Before calling this routine, The name should first be searched for, and then verified, then opportunity given to change the name.
Dim MyPath As String 'String to hold the path to an excel spreadsheet exported from quickbooks
Dim NametoChange As String 'String that holds the name manager name to store the path under
Dim NameComment As String 'Comment to identify the name in the name manager
Dim PathLength As Long
Dim PathTemp As String
NametoChange = "PathToEmployeeWithholding"
NameComment = "This Name contains the Path to the 'Employee Withholding' worksheet exported from quickbooks using VBA"
MyMessage = "If you have not already exported and" & vbCrLf & "saved the employee withholding data from Quickbooks," & vbCrLf & "Please choose cancel and export it now"
DoIt = MsgBox(MyMessage, vbOKCancel)
Debug.Print DoIt
If DoIt = vbCancel Then
Exit Sub
End If
With Application.FileDialog(msoFileDialogFilePicker)
If .Show <> 0 Then
MyPath = .SelectedItems(1)
End If
End With
Debug.Print MyPath 'NOTE:This is producing the correct path. It has no colon here...
'Where is the colon coming from?
'IT SEEMS NECESSARY TO REMOVE A COLON IF THE PATH IS A NETWORK PATH
'FIRST VERIFY IT IS NOT A DRIVE PATH... SHOULD BE IN THE FORM OF D:\
'WHAT IS UNIQUE IS THE COLON IS THE 2ND CHARACTER IN THE PATH IF A LOCAL DRIVE.
'TEST TO SEE IF THE INCREMENT IS 2. IF IT IS, SKIP IT, AND REMOVE ALL OTHER COLONS
PathLength = Len(MyPath)
For i = 1 To PathLength
If Not i = 2 Then
If Not Mid(MyPath, i, 1) = ":" Then
PathTemp = PathTemp & Mid(MyPath, i, 1)
End If
Else
PathTemp = PathTemp & Mid(MyPath, i, 1)
End If
Debug.Print "i = " & i & " The current Character is " & _
Mid(MyPath, i, 1) & xlcrlf & "the current PathTemp is " & PathTemp
Next
MyPath = PathTemp
Debug.Print MyPath
Debug.Print "Calling ChangeValueOfName Routine"; vbCrLf & vbCrLf
Call ChangeValueOfName(NametoChange, MyPath, NameComment) 'this routine stores the retrieved text string in the name manager
Debug.Print "Exit GetPath Routine" & vbCrLf & vbCrLf
End Sub
Sub ChangeValueOfName(NametoChange As String, NewNameValue As String, Comment As String)
Debug.Print "Start changeValueOfName routine"
' ChangeValueOfNameManagerName Macro
' Changes the Value of a defined name in the Name Manager
'This should be used to change the name.
'Once the file is selected data needs to be imported to an array, and the
'Employee name values need to be checked against the worksheets in the workbook and against the recap sheet
'If changes are needed, it needs to write them into the workbook, including changing recap sheet and adding
'worksheets for any new employees
With ThisWorkbook.Names(NametoChange)
.Name = NametoChange
.Comment = Comment
RefersToR1C1 = _
"=" & Chr(34) & NewNameValue & Chr(34)
End With
Debug.Print "The New Path added is " & "=" & Chr(34) & NewNameValue & Chr(34)
Debug.Print "Return from ChangeValueOfName routine" & vbCrLf & vbCrLf
End Sub

VBA Excel - SaveCopyAs method is breaking all Hyperlinks

I have a problem I've been trying to solve for a while now with no luck...!
I have a backup code which saves a copy of a spreadsheet using the application.savecopyas method.
Trouble is, once this is run all the hyperlinks throughout the workbook become invalid as part of the path is removed. Such as this:
CORRECT PATH - file:///\servername\department\project\model\site\comms\filename.pdf
INCORRECT PATH - file:///\servername\department\project\comms\filename.pdf
The problem only occurs when running the following line of code:
ActiveWorkbook.SaveCopyAs FileName:=FullFileName
Where FullFileName is defined earlier in the code by:
FullFileName = FolderPath & "\" & Format(Now, "yyyy-mm-dd_hh-mm-ss") & " - " & FileName & "." & FileExt
Any ideas why the SaveCopyAs would be affecting my hyperlinks in this strange way?
-
FURTHER INFORMATION - Repair Code also does a similar thing:
I also have a fixing code to repair the broken links, essentially this gets the file name and manually combines the correct folder name and filename and assigns this to each hyperlink.
I have noticed this also, sometimes leaves out part of the File Path, sometime it works, othertimes it does not. I don't change anything in the code between runs.
Sub HyperlinkFix_FromCustomer()
j = 0
Dim GetURL As String
For j = 3 To 1000
If IsEmpty(Cells(j, 2)) = False Then
On Error Resume Next
LinkAddress = Sheets("From Customer").Range("B" & j).Hyperlinks(1).Address
If Cells(j, 2).Hyperlinks.Count < 1 Then
'MsgBox j
GoTo Next1
End If
'Sheets("From Customer").Range("W" & j).Value = linkAddress
Inputstring = LinkAddress
'InputString = Sheets("From Customer").Range("W" & j).Value
I = 0
While InStr(I + 1, Inputstring, "\") > 0
I = InStr(I + 1, Inputstring, "\")
Wend
'Extract the folder path
'If No occurence of path separator is found then assign the default directory path
If I = 0 Then
FolderName = "Error - No Folder"
Else
FolderName = Left(Inputstring, I - 1)
End If
'Extracting the file name
FileName = Right(Inputstring, Len(Inputstring) - I)
YearStr = Right(Inputstring, Len(Inputstring) - I + 5)
YearStr = Left(YearStr, 4)
NewDIR = "department\Project\model\site\comms\"
NewDIR = GETNETWORKPATH("D:") & "\" & NewDIR
CorrectAddress = NewDIR & "\" & YearStr & "\" & FileName
Sheets("From Saab").Hyperlinks.Add Anchor:=Sheets("From customer").Range("B" & j), Address:=CorrectAddress, TextToDisplay:=Sheets("From customer").Range("B" & j).Value
End If
Next1:
Next j
End Sub
I just found a solution for this problem.
Go to File --> Info --> Show All Properties --> Hyperlink Base
Write your drive there e.g.
C:\

Excel vba Next invoice number with creation of automatic directory folder by month

Ok , here is the thing,
I have created a next invoice number program in which by pressing of a macro assigned button active invoice automatically saved and closed and the next invoice with a number increased appear.My problem is that, I want excel invoices to be created in their relevant folder by their first two digits of invoice number . as an example : 04-001 where 04 stands for April. also, when invoice number is given 05-002, the directory folder of may 2018-19 should be auto created and invoice should be there in the folder only. i am trying to figure out the code since some time but no luck till now. So far , The invoices are created according to date only but as darren said it is a problem for me when i am trying to create invoices from december on first day of january.
This is my current code :
Sub SaveInvoiceM()
Dim NewFN As Variant
If Len(Dir("C:\Invoices\" & Format(Date, "MMM YYYY") & "-" & (Format(Date, "YY") + 1), vbDirectory)) = 0 Then
MkDir "C:\Invoices\" & Format(Date, "MMM YYYY") & "-" & (Format(Date, "YY") + 1)
End If
' Copy Invoice to a New Workbook
NewFN = "C:\Invoices\" & Format(Date, "MMM YYYY") & "-" & (Format(Date, "YY") + 1) & "\Inv" & Range("F5") & ".xlsx"
ActiveWorkbook.saveas NewFN, FileFormat:=xlOpenXMLWorkbook
NextInvoice
End Sub
Range("F5") stands for my invoice number which is 04-001
I see what you are trying to do (keep nicely organized, automatically) and that's an excellent goal.
I have a suggestion of an alternate invoice numbering system (based on what I'm understanding of your situation & experience level) that will make tasks (like this "auto-filing" process) much easier, and will also simplify the process any time you (or especially anyone else) needs to look back at these invoices. There are a number of obvious benefits (same idea as metric vs imperial).
Ideal numbering system: (in my opinion)
To reduce confusion: Give each invoice and filename the same name instead of having a filename with a month and
Since you want granularity from months to years (but not days): make the invoice/file name include the all of those fields.
To make sorting & finding these logical (easier): place each "date part" in order of biggest to smallest. A unique sequential number goes at the very end.
Your code sample was a good start - I just have a bit of OCD when it comes to this kind of thing, and creation of a numbering system is an important task. (Also this will be "date-proof", and error-checked along the way...
This is a little different than what you had because instead of you telling the code what the next invoice number is, it tells you (by figuring out the next number in sequence based on the existing files).
Like yours, it creates a folder if necessary. Since the files are number YYMM-nnn then are always in the correct order when you sort them. (The "month folders" are unnecessary since the month is in the filename, but I included them anyway since that was your plan. You could just keep every month's invoices in one folder, and they'd still be organized in order of month.)
VBA #1: Save file with next sequential invoice number (creating folder if necessary)
Sub createInvoiceNumberAndSave()
'creates a new invoice number based on date in specified cell & creates new folder if necessary
'finds next unused invoice number & verifies that file is properly saved
Const invoicePath = "c:\invoices\" ' invoice root save path
Const fNamePrefix = "Inv" ' prefix for the filename
Const fNameExt = ".xlsm" ' file extension
Const getInvoiceDate = "F5" ' we GET the DATE of the invoice from F5
Const putInvoiceNumber = "F6" ' we will PUT the new filename into cell F6
Dim invDate As Date, folderName As String, fName As String, fNum As Long, nextInvoiceNum As Long
'get the invoice date and make sure it's valid
If IsDate(Range(getInvoiceDate).Value) Then
'valid date found in cell F5
invDate = Range(getInvoiceDate).Value
Else
'valid date not found in F5. Do we want to default to today's date?
If MsgBox("Cell " & getInvoiceDate & " does not contain a valid date." & vbLf & vbLf & _
"Do you want to use today's date instead?", vbQuestion + vbOKCancel, "Date not found") <> vbOK Then
Call MsgBox("Invoice Not Saved.", vbCritical + vbononly, "User Cancelled")
Exit Sub 'stop running
Else
invDate = Date 'use today's date
End If
End If
'find the next unused invoice number for this month
folderName = Format(invDate, "YYMM")
nextInvoiceNum = 0
'figure out the next unused "file number"
fName = Dir(invoicePath & folderName & "\" & fNamePrefix & folderName & "-*" & fNameExt)
If fName = "" Then
'file not found
If Dir(invoicePath & folderName, vbDirectory) = "" Then
'month not found - create folder?
If MsgBox("Okay to create folder '" & invoicePath & folderName & "' for invoice #" & folderName & "-001 ?", _
vbOKCancel + vbQuestion, "Folder not Found") <> vbOK Then Exit Sub
'create folder
MkDir (invoicePath & folderName)
End If
Else
'month found. Now find the highest invoice number in the folder.
Do While fName <> ""
Debug.Print "Found File: " & fName
'get the number (filename = fNamePrefix & "YYMM-___.xlsx" so we know where it is
If IsNumeric(Mid(fName, 6 + Len(fNamePrefix), 3)) Then 'it's a valid number
fNum = Val(Mid(fName, 6 + Len(fNamePrefix), 3))
'if it's the biggest so far, remember it
If fNum > nextInvoiceNum Then nextInvoiceNum = fNum 'biggest one so far
End If
fName = Dir
Loop
End If
'we have the next available invoice#
nextInvoiceNum = nextInvoiceNum + 1 'new invoice# (numeric)
'PUT the new invoice# (text) in cell F6
Range(putInvoiceNumber).Value = fNamePrefix & folderName & "-" & Format(nextInvoiceNum, "000")
fName = invoicePath & folderName & "\" & Range(putInvoiceNumber).Value & fNameExt
Debug.Print "Saving as: " & fName
'save file
ActiveWorkbook.SaveAs fName
'DOUBLE CHECK check that file exists (couple lines of code now save a headache later)
If Dir(fName) = "" Then
'something went wrong (file wasn't saved)
Call MsgBox("ERROR! FILE NOT SAVED: " & fName, vbCritical + vbOKOnly, "ERROR!")
Stop
End If
'success message!
Call MsgBox("Invoice saved successfully:" & vbLf & vbLf & fName, vbInformation, "Invoice Created")
'NextInvoice '?
End Sub
EDIT: ("Back to your way")
I can think of a number of ways that your method will be a problem, some of which I tried explaining, but you're determined to number & organize these files your way, so "here you go".
VBA #2: Save file with cell value as name:
This procedure saves the current file, named from the invoice number (like 04-001) that you enter in cell F5 (creating folder if necessary):
Sub SaveFileBasedOnInvoiceNumber()
Dim monthNum As Long, yearString As String, folderName As String, fName As String
'build filename
On Error Resume Next 'skip errors for now
monthNum = Val(Left(Range("F5"), 2))
yearString = Year(Date) & "-" & Right(Year(Date) + 1, 2)
folderName = "c:\invoices\" & StrConv(monthName(monthNum, True), vbUpperCase) & " " & yearString
fName = folderName & "\INV" & Range("F5") & ".xlsm"
'check if there was a problem
If Err Then MsgBox "Invalid invoice number": Exit Sub
MkDir (folderName) 'create folder
On Error GoTo 0 'turn error checking back on
'Confirm file saved properly
ActiveWorkbook.SaveAs fName 'save file
If Dir(fName) = "" Then MsgBox "Error! File not saved: " & fName: Exit Sub
MsgBox "Invoice saved successfully:" & vbLf & fName
End Sub
I'll leave "VBA #1" in the the top of the answer for others seeking a logical numbering & storage system with auto-generated invoice numbers.
(One day you'll figure out why that way would've been better, but be forewarned, it will be a lot more of a hassle to change your organization method later!)
Good luck!

Avoid overwriting into a cell

I have created this code to monitor a folder in case of creation and deletion events.
However, the code I created overwrites always the same cell, whereas I would like to keep track of the changes. Hence I would like all the creation events to be listed in column A and the deletion events to be listed in column B.
Can somebody help me?
Select Case objEventObject.Path_.Class
Case "__InstanceCreationEvent"
MsgBox "A new file was just created: " & objEventObject.TargetInstance.PartComponent
Workbooks("MonitorDirectory").Worksheets("Tabelle1").Range("A2") = objEventObject.TargetInstance.PartComponent
Exit Do
Case "__InstanceDeletionEvent"
MsgBox "A file was just deleted: " & objEventObject.TargetInstance.PartComponent
Workbooks("MonitorDirectory").Worksheets("Tabelle1").Range("B2").End(xlDown).Offset(1, 0) = objEventObject.TargetInstance.PartComponent
Exit Do
End Select
adding two variables x,y as below might work
Select Case objEventObject.Path_.Class
Dim i As Integer
x = Range("a" & Rows.Count).End(xlUp).Row + 1
y = Range("b" & Rows.Count).End(xlUp).Row + 1
Case "__InstanceCreationEvent"
MsgBox "A new file was just created: " & objEventObject.TargetInstance.PartComponent
Workbooks("MonitorDirectory").Worksheets("Tabelle1").Range("A" & x) = objEventObject.TargetInstance.PartComponent
Exit Do
Case "__InstanceDeletionEvent"
MsgBox "A file was just deleted: " & objEventObject.TargetInstance.PartComponent
Workbooks("MonitorDirectory").Worksheets("Tabelle1").Range("B" & y).Offset(1, 0) = objEventObject.TargetInstance.PartComponent
Exit Do
End Select

VBscript to monitor system performance leaks memory

I have a simple script that monitors processes' different performance statistics in Windows XP in a loop until it is terminated.
Despite my efforts, the script's memory footprint increases in size over time.
Any advice is greatly appreciated.
Set fso = CreateObject("Scripting.FileSystemObject")
logFileDirectory = "C:\POSrewrite\data\logs"
Dim output
Dim filePath
filePath = "\SCOPerformance-" & Day(Now()) & Month(Now()) & Year(Now()) & ".log"
IF fso.FolderExists(logFileDirectory) THEN
ELSE
Set objFolder = fso.CreateFolder(logFileDirectory)
END IF
logFilePath = logFileDirectory + filePath + ""
IF (fso.FileExists(logFilePath)) THEN
set logFile = fso.OpenTextFile(logFilePath, 8, True)
output = VBNewLine
output = output & (FormatDateTime(Now()) + " Open log file." & VBNewLine)
ELSE
set logFile = fso.CreateTextFile(logFilePath)
output = output & (FormatDateTime(Now()) + " Create log file." & VBNewLine)
END IF
output = output & (FormatDateTime(Now()) + " Begin Performance Log data." & VBNewLine)
output = output & ( "(Process) (Percent Processor Time) (Working Set(bytes)) (Page Faults Per Second) (PrivateBytes) (PageFileBytes)" & VBNewLine)
WHILE (True)
On Error Resume NEXT
IF Err = 0 THEN
strComputer = "."
Set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set objServicesCimv2 = GetObject("winmgmts:\\" _
& strComputer & "\root\cimv2")
Set objRefreshableItem = _
objRefresher.AddEnum(objServicesCimv2 , _
"Win32_PerfFormattedData_PerfProc_Process")
objRefresher.Refresh
' Loop through the processes three times to locate
' and display all the process currently using
' more than 1 % of the process time. Refresh on each pass.
FOR i = 1 TO 3
objRefresher.Refresh
FOR Each Process in objRefreshableItem.ObjectSet
IF Process.PercentProcessorTime > 1 THEN
output = output & (FormatDateTime(Now()) & "," & i ) & _
("," & Process.Name & _
+"," & Process.PercentProcessorTime & "%") & _
("," & Process.WorkingSet) & ("," & Process.PageFaultsPerSec) & _
"," & Process.PrivateBytes & "," & Process.PageFileBytes & VBNewLine
END IF
NEXT
NEXT
ELSE
logFile.WriteLine(FormatDateTime(Now()) + Err.Description)
END IF
logFile.Write(output)
output = Empty
set objRefresher = Nothing
set objServicesCimv2 = Nothing
set objRefreshableItem = Nothing
set objFolder = Nothing
WScript.Sleep(10000)
Wend
I think the main problem with your script is that you initialize WMI objects inside the loop, that is, on every iteration of the loop, even though these objects are always the same:
strComputer = "."
Set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set objServicesCimv2 = GetObject("winmgmts:\\" _
& strComputer & "\root\cimv2")
Set objRefreshableItem = _
objRefresher.AddEnum(objServicesCimv2 , _
"Win32_PerfFormattedData_PerfProc_Process")
You need to move this code out of the loop, e.g., at the beginning of the script.
Other tips and suggestions:
Use Option Explicit and explicitly declare all variables used in your script. Declared variables are slightly faster than undeclared ones.
Use FileSystemObject.BuildPath to combine multiple parts of the path. The useful thing about this method is that it inserts the necessary path separators for you.
logFileDirectory = "C:\POSrewrite\data\logs"
filePath = "SCOPerformance-" & Day(Now) & Month(Now) & Year(Now) & ".log"
logFilePath = fso.BuildPath(logFileDirectory, filePath)
The objFolder variable isn't used in your script, so there's no need to create it. Also, you can make the FolderExists check more readable by rewriting it as follows:
If Not fso.FolderExists(logFileDirectory) Then
fso.CreateFolder logFileDirectory
End If
Move repeated code into subroutines and functions for easier maintenance:
Function DateTime
DateTime = FormatDateTime(Now)
End Function
...
output = output & DateTime & " Open log file." & vbNewLine
Usually you don't need parentheses when concatenating strings:
output = output & DateTime & "," & i & _
"," & Process.Name & _
"," & Process.PercentProcessorTime & "%" & _
"," & Process.WorkingSet & "," & Process.PageFaultsPerSec & _
"," & Process.PrivateBytes & "," & Process.PageFileBytes & vbNewLine
In this article, Eric Lippert (Literally worked on designing and building VBScript at Microsoft) indicates that the order in which you dispose of things may be important. Maybe you are running into one of these bugs?
I'll let you read the rest...
When Are You Required To Set Objects To Nothing?
I would recommend against running the script in a permanent loop within the script unless you actually need such a tight loop. I would suggest a single iteration within in the script, called from Scheduled tasks.
I have run into the exact same issue, using it for a procmon-style attempt to capture a rogue process that appears to be respawning.
Narrowing it all down, it appears to be the objRefresher.Refresh and there simply appears to be no way around it
What I did to overcome this was use a for...next to run it 100 times, then immediately afterwards run the following, which would simply respawn the script and shutdown:
CreateObject("Wscript.Shell").Run """" & WScript.ScriptFullName & """", 0, False
So I would watch the memory crawl from 5Mb to 40Mb, then drop back down to 5Mb

Resources