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.
Related
The code below is used to update several worksheets in different locations. It will update a particular module that I will specify. This code was working good as of last week. But starting this week it is not working anymore. Everytime, I run this code, it will throw an error during saving of the workbook. The error is "run-time error '1004' Document not saved". I did not change the source code, it was puzzling for me because it used to work but now it is not working. Anybody can suggest anything for me to solve this problem? I am guessing maybe because Excel updates itself and there were some changes in the new updates. The microsoft excel that I am using is Microsoft 365 MSO (Version 2209 Build 16.0.15629.20200) 64-bit. Can you guys suggest other code that works that could replace a module in an excel file given the source is in a text file as .bas extension.
Thanks.
Sub Update_VBA_Module_Pricing_Tool()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim wbUpdate As Workbook
Dim ModuleFile As String
Set wsActive = ThisWorkbook.Sheets("Pricing")
'Loop Thru Files Listed in Col A
i = 2
While wsActive.Range("A" & i).Value <> ""
If wsActive.Range("C" & i).Value = "Y" Then
Application.StatusBar = "Updating " & wsActive.Range("B" & i).Value & " ..."
'DirFile = Workbooks.Open(wsActive.Range("A" & i).Value)
If IsFile(wsActive.Range("A" & i).Value) = False Then
MsgBox wsActive.Range("B" & i).Value & " does not exist..."
GoTo proceed_to_next:
End If
'Dim wbTemp As Workbook
'Set wbTemp = Workbooks.Open("D:\Spark RE Analytics, LLC\Spark Vault - General\02-Pricing Properties\Tuesday-pm-G-BLD\1. Pricing Tool\Week 111 22-10-23\1_BLD Portfolio Pricing Tool Week 111.xlsm")
Set wbUpdate = Workbooks.Open(wsActive.Range("A" & i).Value)
Set vbp = Workbooks(wbUpdate.Name).VBProject
'Loop Thru VBA Modules in Col D
j = 2
While wsActive.Range("H" & j).Value <> ""
If wsActive.Range("J" & j).Value = "Y" Then
'Set module to Process
ModuleFile = wsActive.Range("H" & j).Value
modulename = wsActive.Range("I" & j).Value
'Replace Module in Workbook
Set vbp = Workbooks(wbUpdate.Name).VBProject
With vbp.VBComponents
.Remove vbp.VBComponents(modulename)
'.Import ModuleFile
Set temp = .Import(ModuleFile)
temp.Name = modulename
End With
' end of insert other things to file
End If
j = j + 1
Wend
'Save File
wbUpdate.Save
wbUpdate.Close False
Application.StatusBar = "Finished Updating " & wsActive.Range("B" & i).Value & " ..."
End If
proceed_to_next:
i = i + 1
Wend
apps_exit:
MsgBox "Done!"
End Sub
I have a code (seen below at the bottom of this message) built by someone else and it has worked very well in excel 2010 but our administration migrated us to excel 2019. Now the same code produces errors. I have also tried checking if there were new add-ins or references in the reference library in vba but have not found anything that removes the errors or allows the code to execute properly.
The function of the code is basically like this:
The code is linked to a pivot table in a worksheet in a workbook. It will ask the user a few questions such as is this a 'RFQ' and then a msg box will open for them to enter a file name. It then asks the user if they wish to have the data added to another worksheet in the same workbook. After all these are answered the code should open an new workbook and copy/paste over data from a hidden worksheet from the original workbook into this new workbook. This new workbook should become the focus and allow the user to make any other changes before they save and close it.
The code automatically saved the new workbook in a location (using a HLink) that is referenced from a cell on another hidden worksheet in the original workbook.
The errors that take place now is this: "The following features cannot be saved in macro-free workbooks: VB Project To save a file with these features, click No, and then choose a macro-enabled file type in the File type list. To continue saving as a macro-free workbook, click Yes.
If the user says yes, the it says the new workbook that was just created 'already exists in this location. Do you want to replace it?"
If you say yes, everything goes blank and you have to restart excel. If you say no, the vba debugger opens to the end of the code highlighting the last part of the code:
ActiveWorkbook.SaveAs FileName:=HLink _ , FileFormat:"xlOpenXMLWorkbook, CreateBackup:=False
I have tried changing some sections of the code. From this:
`'Save
On Error GoTo ErrFileClose:
HLink = (FilePath & "\" & FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#") & ".xlsx")
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End If`
To this:
'Save
On Error GoTo ErrFileClose:
HLink = (FilePath & "\" & FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#"))
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=51, CreateBackup:=False
End If
And similarly, from this:
'Check if previously created file is open and close it so new one can be saved
ErrFileClose:
FinalFileName = FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#") & ".xlsx"
Workbooks(FinalFileName).Close SaveChanges:=True
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
To this:
'Check if previously created file is open and close it so new one can be saved
ErrFileClose:
FinalFileName = FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#")
Workbooks(FinalFileName).Close SaveChanges:=True
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=51, CreateBackup:=False
These changes sometimes help and seem to remove the vb project error but it is not consistent every time I run the macro.
Any help is appreciated as we cannot move forward using this as it stands.
Thanks.
Sub ImportFile()
'
' ImportFile Macro
Call UnprotectAll
'Create Import
Dim curWorkbook As Workbook
Dim ReqType As String
Dim FileName As String
Dim FinalFileName As String
Dim FilePath As String
FilePath = Sheets("X").Range("C3").Value
Dim HLink As String
Application.ScreenUpdating = False
Sheets("Import").Visible = True
Sheets("Import").Copy
ActiveSheet.Unprotect
'Edit import to remove formulas and blank rows
Range("A1:AC500").Value = Range("A1:AC500").Value
Columns("C:C").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Set curWorkbook = ActiveWorkbook
Windows("Transactions.xlsm").Activate
Sheets("Import").Visible = False
curWorkbook.Activate
'Save Import
ReqType = MsgBox("Click YES if you are creating an RFQ", vbYesNoCancel)
'vbCancel = 2, vbYes = 6, vbNo = 7
If ReqType = 6 Then
ReqType = "RFQ"
Else
If ReqType = 7 Then
ReqType = "Ordered"
Else
Exit Sub
End If
End If
FileName = InputBox("Please enter the Incident number or other Unique ID Number to save this file as:")
'Cancel Save
If FileName = "" Then
ActiveWorkbook.Close SaveChanges:=False
Call ProtectAll
Application.ScreenUpdating = True
MsgBox ("File Not Created")
Exit Sub
Else
'Save
On Error GoTo ErrFileClose:
HLink = (FilePath & "\" & FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#") & ".xlsx")
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End If
'Add Order to Receive tab ?
If MsgBox("Ok to add this data as Transaction: " & ReqType & "?", vbOKCancel) = vbOK Then
Windows("Transactions.xlsm").Activate
Else
'Do Not add Order to transactions Order - Receipt
ActiveWorkbook.Close SaveChanges:=False
Call ProtectAll
Application.ScreenUpdating = True
MsgBox ("This has not been added as a transaction. Click the HuB button when ready to try again. A new import file will be created and can be saved over the one just created.")
Exit Sub
End If
'AddOrder to Transactions Order - Receipt
ActiveSheet.PivotTables("ToBeOrderedPivot").RowRange.Select
'Remove headers and column 1
Selection.Offset(1, 1).Resize(Selection.Rows.Count - 1, _
Selection.Columns.Count).Select
'Remove Extra Columns
Dim FirstRow As Integer
Dim LastRow As Integer
FirstRow = Selection.Row
LastRow = FirstRow + Selection.Rows.Count - 1
Range("C" & FirstRow & ":F" & LastRow & ",AA" & FirstRow & ":AA" & LastRow & ",L" & FirstRow & ":L" & LastRow).Select
Selection.SpecialCells(xlCellTypeVisible).Copy
'Move to end of Orders table
Sheets("Receive").Select
Count = Range("Orders[Mtl ID]").Rows.Count
Range("B" & Count + 4).Select
'Paste Values
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
'Set Values
Selection.Offset(0, 8).Columns(1).Value = Selection.Offset(0, 2).Columns(1).Value
If ReqType = "RFQ" Then
Selection.Offset(0, 2).Columns(1).Value = 0
Selection.Offset(0, 7).Columns(1).Value = ReqType
Else: Selection.Offset(0, 2).Columns(1).Value = Selection.Offset(0, 5).Columns(1).Value
End If
Selection.Offset(0, 5).Columns(1).Value = Selection.Offset(0, 3).Columns(1).Value
Selection.Offset(0, 3).Columns(1).Value = Selection.Offset(0, 4).Columns(1).Value
Selection.Offset(0, 4).Columns(1).Value = Selection.Offset(0, 8).Columns(1).Value
Selection.Offset(0, 8).Columns(1).Value = FileName
Selection.Offset(0, 9).Columns(1).Value = Format(Date, "[$-409]yyyy-mm-d;#")
'Sort Table
Call SortReceive
Call ProtectAll
Application.ScreenUpdating = True
'Return to Import File
curWorkbook.Activate
Exit Sub
'Check if previously created file is open and close it so new one can be saved
ErrFileClose:
FinalFileName = FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#") & ".xlsx"
Workbooks(FinalFileName).Close SaveChanges:=True
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Resume Next
End Sub
Thanks for all the help given here.
I am by no means a coder and spend hours searching forums and canabilising bits of code to create what I need. I built the below code to extract data from one workbook, based on the filter and then save as in a individual workbooks. This code worked really well for one workbook, but now I've tried to reuse it,it throws a 1004 runtime error when trying to save as. Any idea where it could be going wrong?
Many thanks,
Stephen
Sub Split()
Dim ws As Worksheet
Dim wsNew As Workbook
Dim rData As Range
Dim rfl As Range
Dim state As String
Dim myValue As Variant
Dim sfilename As String
Dim FolderName As String
Dim strDir As String
myValue1 = InputBox("What date is this save for? (Format: DD Month)")
Range("B1").Select
Selection.AutoFilter
Set ws = ThisWorkbook.Sheets("Combined Data")
With ws
Set rData = .Range(.Cells(1, 2), .Cells(.Rows.Count, 13).End(xlUp))
.Columns(.Columns.Count).Clear
.Range(.Cells(2, 6), .Cells(.Rows.Count, 6).End(xlUp)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=.Cells(1, .Columns.Count), Unique:=True
MsgBox "Please select the folder to save files"
FolderName = GetFolder()
If FolderName = "" Then
MsgBox "No folder was selected. Program will terminate."
Exit Sub
End If
For Each rfl In .Range(.Cells(2, .Columns.Count), .Cells(.Rows.Count, .Columns.Count).End(xlUp))
state = rfl.Text
strDir = FolderName & "\" & state
If Dir(strDir, vbDirectory) = "" Then
MkDir strDir
Else
End If
Set wsNew = Workbooks.Add
sfilename = "Monday" & " " & myValue1 & " - Engagement" & ".xlsx"
ActiveWorkbook.SaveAs strDir & "\" & sfilename
You need to find out the actual reason for this common error code - 1004. Edit your function/VBA code and run your program in debug mode to identify the line which is causing it. And then, add below piece of code to see the error,
On Error Resume Next
// your code goes here which causes 1004 error
If Err.Number > 0 Then
Debug.Print Err.Number & ":" & Err.Description
End If
I'd suggest using debug shortcut keys on your keyboard - Step Into (F8), Step Over (Shift + F8), Step Out (Ctrl + Shift + F8)
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 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