I have written an Excel VBA macro that compiles all the information from various spreadsheets that are located in a specific folder and compiles them into one 'Master' Excel workbook.
This currently works fine when using it on my computer, but I would like to adjust the code so that I can place the 'Master' spreadsheet and the folder containing the individual spreadsheet (the ones to be compiled) on a network drive, so that anyone can use it.
I am fairly new to VBA and coding in general so I have a strong feeling there is probably an easy solution to fix my issue.
I have attached my current macro that runs the absolute reference.
'Summary: Open all Excel files in a specific folder and merge data
' into one master sheet (stacked)
Dim fName As String, fPath As String, fPathDone As String, OldDir As String
Dim LR As Long, NR As Long
Dim wbData As Workbook, wbkNew As Workbook
'Setup
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Set wbkNew = ThisWorkbook
wbkNew.Activate
Sheets("Master").Activate
If MsgBox("Import new data to this report?", vbYesNo) = vbNo Then Exit Sub
If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
Cells.Clear
NR = 1
Else
NR = Range("A" & Rows.Count).End(xlUp).Row + 1
End If
fPath = "C:\Folder-that-Excel-workbooks-are-located-in"
On Error Resume Next
MkDir fPathDone
On Error GoTo 0
OldDir = CurDir
ChDir fPath
fName = Dir("*.xlsx")
Do While Len(fName) > 0
If fName <> wbkNew.Name Then
Set wbData = Workbooks.Open(fName)
LR = Range("C" & Rows.Count).End(xlUp).Row
If NR = 1 Then
Range("C5:F" & LR).EntireRow.Copy _
wbkNew.Sheets("Master").Range("A" & NR)
Else
Range("C5:F" & LR).EntireRow.Copy _
wbkNew.Sheets("Master").Range("A" & NR)
End If
wbData.Close False
NR = Range("C" & Rows.Count).End(xlUp).Row + 1
fName = Dir
End If
Loop
ErrorExit:
ActiveSheet.Columns.AutoFit
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
ChDir OldDir
One quick and dirty solution would be putting the path to the workbook folder somewhere into the master workbook.
Put the other workbooks on a network share that is available to all computers you are sharing your excel sheet with. Use a UNC path like this:
\\ComputerName\SharedFolder\Resource
You can then set fPath in your code to the cells value.
A better way would be putting the path into a settings file in the same folder as the master workbook and reading the path when running the macro:
Dim tmpArray() As String
Dim s As String
Dim strPath as String
Open ThisWorkbook.Path & "\settings.ini" For Input As #1
Do While Not EOF(1)
Line Input #1, s
If VBA.Left(s, 11) = "excelfolder" Then
tmpArray = Split(s, "=")
strPath = tmpArray(1)
End If
Loop
Close #1
Your ini file would look like this:
excelfolder=\\ComputerName\SharedFolder\Resource
Related
I have created a script that splits a large Excel database into 30 rows, creates a new workbook for it.
and checks if there is a folder based on cell value if not then it creates it.
after all of that I want to save my files in that same new folder he created/checked for.
but for some reason after creating a string named path and populating it with the location.
I am receiving an EXPECTED ARRAY error when stating that I want to save it in the path value location.
Public Sub Split_30()
Dim inputFile As String, inputWb As Workbook
Dim lastRow As Long, row As Long, n As Long
Dim newCSV As Workbook
Dim FileN As String
Dim path As String
FileN = Range("O2").Value
path = "C:\OrderCargo\" & Range("O2").Value
Application.ScreenUpdating = False
inputFile = "C:\OrderCargo\Original\ãåç øëù î÷åøé" 'CHANGE TO YOUR INPUT FILE, OR USE GETOPENFILENAME
Set inputWb = Workbooks.Open(inputFile)
With inputWb.Worksheets(1)
lastRow = .Cells(Rows.Count, "A").End(xlUp).row
Set newCSV = Workbooks.Add
n = 0
For row = 1 To lastRow Step 30
n = n + 1
.Rows(row & ":" & row + 30 - 1).EntireRow.Copy newCSV.Worksheets(1).Range("A1")
If Dir(path, vbDirectory) = "" Then
Shell ("cmd /c mkdir """ & path & """")
End If
**newCSV.SaveAs FileName:=path**(inputWb.FullName, ".xlsx", " " & Format(Date, "mmm") & " " & FileN & "(" & n & ").csv"), FileFormat:=xlCSV, CreateBackup:=False
Next
End With
newCSV.Close saveChanges:=False
inputWb.Close saveChanges:=False
End Sub
Can anyone please try and help me find the error..
I think you have a race condition. The shell execution "mkdir" might not be finished before trying to save. Try the VBA command mkdir instead.
I created a VBA macro that formats and creates charts out of raw data. I have added functionality to track usage of the macro and record usage (username, timestamp, client name) to a .txt file on our database.
The problem I am running into is that I want the usage tracker to be blind to the end user. However, I am getting windows popping up showing a save bar to the directory path. I've tried searching around for a solution to keep this hidden but I am unable to find any code that I'm able to implement to solve.
I expected the following inputs to hide all windows. I am not quite sure if I need more elaborate code to hide the save window.
Application.DisplayAlerts = False
Application.DisplayStatusBar = False
Application.ScreenUpdating = False
Application.EnableEvents = False�
Here is the code Im using to save usage:
'Usage Tracker'
On Error Resume Next
Dim wb As Workbook: Set wb = ActiveWorkbook
''''tracking file location
Dim strFilename As String: strFilename = "\\Ant\dept\CorporateDevelopment\BizDev\In-Shipment\ISO\zz_File_Location\macrotracking.txt"
Dim recordFile As Workbook
Set recordFile = Workbooks.Open(Filename:=strFilename)
Dim LastRow As Long
LastRow = recordFile.Sheets("macrotracking").Range("A1").SpecialCells(xlCellTypeLastCell).Row
wb.Activate
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "Performance" Then
exists = True
End If
Next i
If exists Then
Advertiser_Name = Sheets("Performance").Range("C3").Value
Else
Advertiser_Name = Sheets("Raw Data").Range("J2").Value
End If
MsgBox wb.Name & exists & Advertiser_Name
''''''these are the variables you want to track, just separate by '& ; &'
recordFile.Sheets("macrotracking").Range("A" & LastRow + 1).Value = Environ("USERNAME") & ";" & Format(Now(), "m/dd/yyyy") & ";" & Format(Now(), "hh:nn:ss") & ";" & ActiveSheet.Range("C3").Value & ";" & "TOTAL"
recordFile.Sheets("macrotracking").Range("A" & LastRow + 1).TextToColumns Destination:=Range("A" & LastRow + 1), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, Semicolon:=True
recordFile.Save
recordFile.Close savechanges:=True
If Err <> 0 Then
Err.Clear
End If
On Error GoTo 0
'End Tracker'
I would greatly appreciate it if someone can help me learn how to hide all windows for this entire macro.
I have a macro code to open several excel sheets one after the other (I only show 3 here):
Sub Macro1()
Workbooks.Open Filename:=Range("F19").Value, UpdateLinks:=0
ActiveWindow.Visible = True
Windows("Data Quality Checks - ITS v2.8.xlsm").Activate
Workbooks.Open Filename:=Range("F21").Value, UpdateLinks:=0
ActiveWindow.Visible = True
Windows("Data Quality Checks - ITS v2.8.xlsm").Activate
Workbooks.Open Filename:=Range("F23").Value, UpdateLinks:=0
ActiveWindow.Visible = True
Windows("Data Quality Checks - ITS v2.8.xlsm").Activate
End Sub
The 'Range' shows the cell with the specific file path.
Currently, if the macro does not find one of the files, it produces an error and the process is forced to stop. Is it possible to include an additional line code that if the file is not found in the specified path, then the process continues and does not stop (no debugging)?
This may helps:
Option Explicit
Sub Macro1()
Dim LastRow As Long, i As Long
Dim PathName As String, MissingFiles As String
With ThisWorkbook.Worksheets("Sheet1")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = 19 To LastRow Step 2 '<- Start from 19 like the example and stop lastrow column A sheet 1. Loop every two.
PathName = .Range("A" & i).Value
If Len(Dir(PathName)) = 0 Then '<- Make sure you add the extension of the file.
If MissingFiles = "" Then
MissingFiles = PathName
Else
MissingFiles = MissingFiles & vbNewLine & PathName
End If
Else
Workbooks.Open Filename:=PathName, UpdateLinks:=0
ActiveWindow.Visible = True
' Windows("Data Quality Checks - ITS v2.8.xlsm").Activate
End If
Next i
MsgBox "Missing Files are: " & vbNewLine & MissingFiles
End With
End Sub
Sheet Structure:
Message Box :
I have some folders with hundreds of reports - all reports are the same, and there´s nothing else in that folders.
I should take multiple workbooks like the first one in the image, and recopilate them in a master file (second image).
I have some code - below - but I don´t know how to complete it; The workbook is a template, so it always have 15 rows (could be completed or not) and I need to bring all that´s there plus the date and group control, which is shared by every document inside the file.
I´d appreciate if you could help me complete the code; somebody told me this could be done using powerquery but I´ve never used it. If you think this would be easier, please let me know your thoughts.
Thanks!!
What I have:
Public Sub test()
'DECLARE AND SET VARIABLES
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Path = "C:\Users\Maudibe\Desktop\ExcelFiles\"
Filename = Dir(Path & "*.xlsm")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Len(Filename) > 0 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & Filename)
'
' **WHAT TO DO HERE?**
'
MsgBox Filename & " has opened"
wbk.Close True
Filename = Dir
Loop
End Sub
So i modified your code to this: (Has to be in ThisWorkbook)
Public Sub test()
'DECLARE AND SET VARIABLES
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim sht, msht As Worksheet
Dim lRowFile, lRowMaster As Long
Dim FirstDataSet As Integer
Path = "C:\Users\User\Desktop\Files\"
Filename = Dir(Path & "*.xlsm")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Filename <> "" And Filename <> "Master.xlsm" 'Dont Open MasterFile 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & Filename)
Set sht = Workbooks(Filename).Worksheets(1) 'First Sheet in File
Set msht = ThisWorkbook.Worksheets(1) 'First Sheet in Master
lRF = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 'Last Row in File
lRM = msht.Cells(Rows.Count, 1).End(xlUp).Row 'Last Row in Master
FirstDataSet = 5 'First Data Set in File
For i = FirstDataSet To lRF
lRM = msht.Cells(Rows.Count, 1).End(xlUp).Row 'Last Row in Master
msht.Range("A" & lRM + 1).Value = sht.Range("A" & i).Value 'DocumentName
msht.Range("B" & lRM + 1).Value = sht.Range("B" & i).Value 'Amount
msht.Range("C" & lRM + 1).Value = sht.Range("D2").Value 'Date
msht.Range("D" & lRM + 1).Value = sht.Range("D3").Value 'Group #
Next i
wbk.Close True
Filename = Dir
Loop
End Sub
It will open the workbooks and check which rows are filled in Col A (Non used have to be blank). Then it copies the Data to the Master File. My Workbooks that have been opened looked like this and the Result:
I am attempting to use VBA to open all the excel files in a directory (in this case c:\temp) and put all the files datasheets in one large file. Each new sheet is named with the filename plus the name of the sheet on the original document. The code that I have copies the first file's first sheet and even names it correctly, but then fails with a Run-time error 1004: Application defined or object defined error on the second sheet when I try to set the name. Anyone have any suggestions on how to fix.
Sub MergeAllWorkbooks()
Dim FolderPath As String
Dim FileName As String
' Create a new workbook
Set FileWorkbook = Workbooks.Add(xlWBATWorksheet)
' folder path to the files you want to use.
FolderPath = "C:\Temp\"
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.xl*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
Dim currentSheet As Worksheet
Dim sheetIndex As Integer
sheetIndex = 1
Windows(WorkBk.Name).Activate
For Each currentSheet In WorkBk.Worksheets
currentSheet.Select
currentSheet.Copy Before:=Workbooks(FileWorkbook.Name).Sheets(sheetIndex)
FileWorkbook.Sheets(sheetIndex).Name = FileName & "-" & currentSheet.Name
sheetIndex = sheetIndex + 1
Next currentSheet
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = Dir()
Loop
End Sub
Replace
FileWorkbook.Sheets(sheetIndex).Name = FileName & "-" & currentSheet.Name
with (I separated it out for readability)
sWSName = FileName & "-" & currentSheet.Name
sWSName = NameTest(sWSName)
sWSName = TestDup(sWSName)
FileWorkbook.Sheets(sheetIndex).Name = sWSName
You will need to define the sWSName.
Below are the modified functions I have previously used.
Function NameTest(sName As String) As String
NameTest = sName
aSpecChars = Array("\", "/", "*", "[", "]", ":", "?")
For Each c In aSpecChars
NameTest = Replace(NameTest, c, "")
Next c
If Len(sName) > 31 Then NameTest = Left(sName, 31)
End Function
Function TestDup(sWSName As String) As String
TestDup = sWSName
For Each ws In Worksheets
Debug.Print ws.Name
If sWSName = ws.Name Then TestDup = TestDup(Left(sWSName, Len(sWSName) - 1))
Next ws
End Function
If posting this code (or to this extent) is out of line please let me know as I am still coming to terms with the level of effort require versus reasonable response.