The macro copies over the sheets to a newly created workbook, I send this report that is WITHOUT MACROS.
However, my client says she has to open the file to enable macros and then re-save.
She says she has a "file linked to the report," so prob. a program that pulls data from the closed report.
She also sent me a photo of her screen with the little yellow bar prompting her that the file is in protected view.
Is there any reason in my code that explains this situation?
Here is my code:
Sub Generate_Position_Report()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.Calculate
Do While Application.CalculationState <> xlDone
DoEvents
Loop
''''''''' Open Previous Report '''''''''
Dim d As Date
d = DateAdd("d", -1, Date)
Dim d3 As Date
d3 = d - 2
Dim prev_file As String
Dim prev_file_exists As String
prev_file = "X:\Risk\Departmental\Reporting\Position Report " & Format(d, "yyyy-mm-dd") & ".xlsx"
prev_file_exists = Dir(prev_file)
If prev_file_exists <> "" Then
Workbooks.Open Filename:="X:\Risk\Departmental\Reporting\Position Report " & Format(d, "yyyy-mm-dd") & ".xlsx"
Else
Workbooks.Open Filename:="X:\Risk\Departmental\Reporting\Position Report " & Format(d3, "yyyy-mm-dd") & ".xlsx"
End If
ThisWorkbook.Activate
''''''''' Variables '''''''''
sim_date = Range("SIM_DATE").Value
main_analysis_name = Range("MAIN_ANALYSIS_NAME").Value
secondary_analysis_name = Range("SECONDARY_ANALYSIS_NAME").Value
previous_workday = Range("PREVIOUS_WORKDAY").Value
t_minus_2_workday = Range("T_MINUS_2_WORKDAY").Value
previous_day_quotes = Range("PREVIOUS_DAY_QUOTES").Value
t_minus_2_quotes = Range("T_MINUS_2_DAY_QUOTES").Value
price_curves_analysis = Range("PRICE_CURVES_ANALYSIS").Value
previous_analysis_date = Range("PREVIOUS_ANALYSIS_DATE").Value
previous_analysis_name = Range("PREVIOUS_ANALYSIS_NAME").Value
col_shift = Range("COL_SHIFT").Value
Application.DisplayAlerts = False
''''''''' Recalculate Data '''''''''
Application.Calculate
Do While Application.CalculationState <> xlDone
DoEvents
Loop
'''''''''' Save the Template ''''''''''
'good practice to turn things back on for the template'
Application.DisplayAlerts = True
Application.ScreenUpdating = True
ThisWorkbook.Save
'we need to turn them off again to finalize the report'
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'''''''''' Copy/Paste Values ''''''''''
'we need to copy and paste values for all the worksheets'
For Each ws In Worksheets
Sheets(ws.Name).Activate
Sheets(ws.Name).Cells.Copy
Sheets(ws.Name).Cells.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Sheets(ws.Name).Cells(1, 1).Select
Next
'''''''''' Create Fresh Copy Without Macros ''''''''''
ThisWorkbook.Sheets.Copy
Application.DisplayAlerts = False
Application.ScreenUpdating = False
ActiveWorkbook.SaveAs Filename:="X:\Risk\Departmental\Reporting\Position Report (TEST) " & Format(d + 1, "yyyy-mm-dd") & ".xlsx", FileFormat:=51
'physically breaking links'
Dim wb As Workbook
Set wb = Application.ActiveWorkbook
If Not IsEmpty(wb.LinkSources(xlExcelLinks)) Then
For Each link In wb.LinkSources(xlExcelLinks)
wb.BreakLink link, xlLinkTypeExcelLinks
Next link
End If
'''''''''' Activate/Hide/Delete Tabs ''''''''''
Worksheets("Control").Visible = False
Worksheets("Reference").Visible = False
Worksheets("HERITAGE Summary").Activate
'turning back on some features for the active/report'
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
ActiveWorkbook.Save 'saving the report'
Workbooks(2).Close 'closes the prev. file'
ThisWorkbook.Close savechanges:=False 'closes the template'
End Sub
Related
I have a macro that consolidates a number of workbooks into a single consolidated file. Originally it was a copying and pasting but I changed it thinking the copying and pasting was too heavy on the computer and was causing it to crash. After successfully implementing the changes the macro continues to fail after cycling through around the 50th workbook. Any insight into with why my excel crashes (closes and opens) using this macro is greatly appreciated.
Note: This macro works on a peer's computer who uses excel 2010
Dim TargetFolder As String, TargetFile As String
Dim wsConsol As Worksheet
Dim CopyLastRow As Long, DestLastRow As Long
Dim TranRange As Variant
'Sets the name of the wsConsol file, if required
Set wsConsol = Workbooks("Consolidation File.xlsm").Worksheets("Raw Data")
'Opens a file dialog box for user to select a folder
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
TargetFolder = .SelectedItems(1)
Err.Clear
End With
'stops screen updating, calculations, events, and status bar updates to help code run faster
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.CutCopyMode = False
'This section will loop through and open each file in the folder you selected
'and then close that file before opening the next file
TargetFile = Dir(TargetFolder & "\", vbReadOnly)
Do While TargetFile <> ""
DoEvents
On Error GoTo 0
Workbooks.Open Filename:=TargetFolder & "\" & TargetFile, UpdateLinks:=False
''''''''''''START CODE HERE TO DO SOMETHING'''''''''
'Find the last row in the wsConsol file
DestLastRow = wsConsol.Cells(wsConsol.Rows.Count, "A").End(xlUp).Offset(1).Row
wsConsol.Range("A" & DestLastRow).Value = Workbooks(TargetFile).Worksheets("Summary").Range("B22:B22").Value
wsConsol.Range("AD" & DestLastRow).Value = Workbooks(TargetFile).Worksheets("Summary").Range("B17:B17").Value
wsConsol.Range("B" & DestLastRow).Value = Workbooks(TargetFile).Worksheets("Summary").Range("B20:B20").Value
TranRange = Workbooks(TargetFile).Worksheets("Summary").Range("D25:L25").Value
TranRange = Application.WorksheetFunction.Transpose(TranRange)
wsConsol.Range("C" & DestLastRow & ":K" & DestLastRow).Value = TranRange
TranRange = Workbooks(TargetFile).Worksheets("Summary").Range("F17:F22").Value
TranRange = Application.WorksheetFunction.Transpose(TranRange)
wsConsol.Range("L" & DestLastRow & ":Q" & DestLastRow).Value = TranRange
TranRange = Workbooks(TargetFile).Worksheets("Summary").Range("G17:G22").Value
TranRange = Application.WorksheetFunction.Transpose(TranRange)
wsConsol.Range("R" & DestLastRow & ":W" & DestLastRow).Value = TranRange
TranRange = Workbooks(TargetFile).Worksheets("Summary").Range("H17:H22").Value
TranRange = Application.WorksheetFunction.Transpose(TranRange)
wsConsol.Range("X" & DestLastRow & ":AD" & DestLastRow).Value = TranRange
''''''''''''END CODE HERE THAT DID SOMETHING'''''''''
'Close TargetFile Workbook
Workbooks(TargetFile).Close SaveChanges:=False
TargetFile = Dir
Loop
'turns settings back on that you turned off before looping folders
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationManual
End Sub
I'm building an automated request form and am running into a headache that only triggers for other users. 3 others receive a run-time error and I cannot figure out what is going on as I've used basically this same script in other books without ever having an issue reported.
Sub tracker_upload()
ActiveWindow.ScrollRow = 1
Run "processing" 'basic UF to display status
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
Run "archive" 'saves completed form to a SP folder
With WaitForm
.lbStatus.Caption = "...archiving form to shared drive"
.Repaint
End With
Application.Wait (Now + TimeValue("00:00:02"))
With Form
If .Priority_Critical_YN = True Then
p = "Critical"
ElseIf .Priority_Must_Have_YN = True Then
p = "High"
ElseIf .Priority_Need_YN = True Then
p = "Medium"
ElseIf .Priority_Nice_YN = True Then
p = "Low"
End If
.Shapes("upload").Visible = False
End With
With Range("tbData")
uID = .Cells(1).Value
.Cells(2) = "New"
.Cells(3) = p
.Cells(9) = Environ$("UserName")
.Cells(10) = Date
.Hyperlinks.Add .Cells(1), ThisWorkbook.FullName, TextToDisplay:=uID
End With
With WaitForm
.lbStatus.Caption = "...updating tracker information"
.Repaint
End With
Dim wb1 As Workbook, wb2 As Workbook
On Error Resume Next
Set wb1 = ActiveWorkbook
Set wb2 = Workbooks("Requests Tracker")
'detect if workbook is already open and open if not
If wb2 Is Nothing Then
Application.Workbooks.Open ("My Shared Drive Location\Requests Tracker.xlsx"), ignorereadonlyrecommended = True
Set wb2 = Workbooks("Requests Tracker")
End If
On Error GoTo 0
wb1.Sheets("data").Range("tbData").Copy
With wb2
.Activate
With .Sheets("Requests")
If .Range("tbTracker").Cells(1) = "" Then
lastrow = .Range("A" & Rows.Count).End(xlUp).Row
Else: lastrow = .Range("A" & Rows.Count).End(xlUp).Row + 1
End If
.Range("A" & lastrow).PasteSpecial xlPasteAllUsingSourceTheme
.Columns.AutoFit
End With
.Save
.Close True
End With
Set wb2 = Nothing
On Error GoTo 0
With Application
.CutCopyMode = False
.ScreenUpdating = True
.DisplayAlerts = True
.Wait (Now + TimeValue("00:00:02"))
End With
Unload WaitForm
wb1.Save
mb = MsgBox("This request has been successfully recorded on the Tracker" & vbCrLf _
& vbCrLf _
& "The form will now close, would you like to open the tracker now?", vbYesNo + vbInformation, "completed")
If mb = vbYes Then
Application.Workbooks.Open ("My Shared Drive Location\Requests Tracker.xlsx"), ignorereadonlyrecommended = True
End If
If Application.Windows.Count = 1 Then
wb1.Saved = True
Application.Quit
Else: wb1.Close False
End If
End Sub
initially it was getting hung up on the .Sheets("Requests") line, then the line below it. It was the decimal in front of each, which I found really bizarre as I've never come across this before. Sure enough, after leaving the .Save and .Close True with decimals, it triggered another error on the next function preceded by a decimal as shown below.
UPDATE: I parsed out the bit of code where I set wb1 and wb2 as I identified it was wb2 that was giving the user an error. I did some testing with several other users who had no issue setting & identifying wb2 as Workbooks("Requests Tracker"). I finally got the sub to pass by adding the file extension to the end of the Workbook name. Why would this be required for this user only?
I had to specify set wb2 = "Requests Tracker.xlsx" in order for the user to not hit a run-time error. I do not know why .xlsx had to be added for this one user and no one else in the entire department...but that resolved the headache.
I have "Filling form" worksheet where user is filling information and then I have "Print version" worksheet that is actually printing. I am making "CV tool" so user is filling his personal information and then my current VBA is saving end file from "Print version" to xls. and .pdf to the same folder with certain name both files where my "CV tool" is. Some people have experience of 10 years in 10 different work places and others have been only in 2 different companies previously. So before saving to .pdf and .xls my VBA hides rows that are empty to make end result look good.
The problem is that estetically it is not so good looking because some heading of work positions are at the end of the page and work description is continuing on the next page. Is there any way to make some kind of VBA to look for each page in "PrintArea" and if certain block is not fitting to this page VBA will insert "Page Break" before it to move it to the next page?
My current macro below (Sub doitallplease() is main command):
Sub Color()
Dim myRange As Range
Dim cell As Range
Set myRange = ThisWorkbook.Sheets("Print version").Range("Print_Area")
For Each cell In myRange
myRange.Interior.ColorIndex = 0
If cell.HasFormula = True And cell.value = "" And cell.EntireRow.Hidden = False Then Rows(cell.Row).EntireRow.Hidden = True
Next
End Sub
Sub MagicButton()
Dim iFileName$, iRow&, iCol&, iCell As Range, iArr
iFileName = ThisWorkbook.Path & "\CV_" & Sheets("Filling form").Range("F7") & "_" & Sheets("Filling form").Range("F9") & ".xls"
iArr = Array(1, 3, 4): iCol = UBound(iArr) + 1
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlManual
ThisWorkbook.Sheets("Print version").Copy
With ActiveWorkbook.ActiveSheet
.Buttons.Delete '.Shapes("Button 1").Delete
.UsedRange.value = .UsedRange.value
.SaveAs iFileName, xlExcel8: .Parent.Close
End With
Application.Calculation = xlAutomatic
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Sub exportpdfthisfile()
ActiveWorkbook.Sheets("Print version").Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\CV_" & Sheets("Filling form").Range("F7") & "_" & Sheets("Filling form").Range("F9") & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Sub doitallplease()
Application.ScreenUpdating = False
ActiveWorkbook.Sheets("Print version").Visible = True
Call Color
Call MagicButton
Call exportpdfthisfile
ActiveWorkbook.Sheets("Filling form").Activate
ActiveWorkbook.Sheets("Print version").Visible = False
Application.ScreenUpdating = True
End Sub
I'm searching for a code to run the same macro on 200+ files in the same folder directory until the last file is complete.
The macro I have currently does this once I click a button
Refresh .CSV data connection (File Selection window pops up in
the directory, I select the file)
Refreshes Pivot Table
Deletes Specific Tabs
Saves Copy As in another Directory
I want to eliminate me clicking the RUN button 200+ times, and selecting the .CSV file. Would anyone happen to know of a code that could do this?
Current MACRO is:
Sub Load_Brand3()
' Load_Brand3 Macro
Sheets("Data").Select
Range("DATATable[[#Headers],[Datetime]]").Select
Selection.ListObject.TableObject.Refresh
Sheets("Brand Summary").Select
Range("A13").Select
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
ActiveSheet.PivotTables("PivotTable1").PivotFields("Retailer.Name").ShowDetail _
= False
Sheets("Brand Summary").Select
Dim SavedCopy As Excel.Workbook
ActiveWorkbook.SaveCopyAs "C:\Users\ME" & Format(Date, "mmddyyyy") & "-" & [A1] & ".xlsm"
Workbooks.Open "C:\Users\ME" & Format(Date, "mmddyyyy") & "-" & [A1] & ".xlsm"
Set SavedCopy = ActiveWorkbook
With SavedCopy
ActiveWorkbook.Connections("BrandExport").Delete
Application.DisplayAlerts = False
.Worksheets("Lookup").Delete
.Worksheets("Count").Delete
Sheets("Brand Summary").Select
Range("A1").Select
Application.DisplayAlerts = True
.Close True
End With
MsgBox ("Your File was saved.")
End Sub
This should be close. Just change MyPath to the correct directory and run ProcessFiles.
Sub ProcessFiles()
Const MyPath As String = "C:\Users\best buy\Data Files\*.csv"
Dim FileName As String
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.DisplayAlerts = False
End With
FileName = Dir(MyPath, vbDirectory)
Do While FileName <> ""
Load_BrandFile FileName
FileName = Dir()
Loop
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
.DisplayAlerts = True
End With
End Sub
Sub Load_BrandFile(FileName As String)
Dim SavedCopy As Workbook
Dim DATATable As ListObject
Dim PivotTable1 As PivotTable
ThisWorkbook.SaveCopyAs "C:\Users\ME" & Format(Date, "mmddyyyy") & "-" & [A1] & ".xlsm"
Set SavedCopy = Workbooks.Open("C:\Users\ME" & Format(Date, "mmddyyyy") & "-" & [A1] & ".xlsm")
With SavedCopy
Set DATATable = .Worksheets("Data").ListObjects("DATATable")
DATATable.Refresh
Set PivotTable1 = .Worksheets("Brand Summary").PivotTables("PivotTable1")
PivotTable1.PivotCache.Connection = FileName
PivotTable1.PivotFields("Retailer.Name").ShowDetail = False
.Connections("BrandExport").Delete
.Worksheets("Lookup").Delete
.Worksheets("Count").Delete
Application.Goto Reference:=.Worksheets("Brand Summary").Range("A1"), scroll:=True
.Close True
End With
End Sub
Hopefully this sorts it for you.
Sub CycleFolder()
Dim folderSelect As FileDialog
Set folderSelect = Application.FileDialog(msoFileDialogFolderPicker)
With folderSelect
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub
strItem = .SelectedItems(1)
End With
Files = Dir(strItem & "\")
While Files <> ""
'RUN FUNCTION HERE
'Uncomment next line to test iteration
'Debug.Print Files
Files = Dir
Wend
End Sub
I import from Access to Excel a data (tables) file, but I don't manage to remove the filter. I get a 1004 error (Delete of Range is failed). I also can't remove it by hand.
Sub Openaccessdatafile()
'Niet blad updaten
Application.ScreenUpdating = False
Sheets.Add.Name = "Gegevens alginaten"
Set sh = ThisWorkbook.Sheets("Gegevens alginaten")
LR = sh.Cells(Rows.Count, "A").End(xlUp).Row
Filename = Application.GetOpenFilename("Excel files (*.xls*), *.xls*")
MsgBox Filename
If Filename <> False Then
Workbooks.Open (Filename)
ActiveSheet.UsedRange.Copy sh.Range("A" & LR)
ActiveWorkbook.Close
Sheets("Start").Cells(2, 5).Value = "Ok"
Else
MsgBox "Geen bestand aangeklikt."
Application.DisplayAlerts = False
Sheets("Gegevens alginaten").Delete
Application.DisplayAlerts = True
End If
'Wel blad updaten
Application.ScreenUpdating = True
Sheets("Start").Select
End Sub
Apparently exporting it with Access through a VBA macro button does work better. Than I could remove the row, because the filter is than not added in the exported file.