Excel VBA Copying sheet from closed workbook to current workbook, but copies outdated sheet - excel

I am on Excel 2003 should that make a difference.
I have a small function that opens a file by path, copies over its first (and only) sheet to the current workbook. Closes the opened template and renames the newly created sheet.
The thing is when it does this the new sheet that is made is and older version of the template file?
The file is located at "E:\Cascade\RunSheet-Heath Edition\CH54\CH54_Template.xlt"
Sub LoadTemplate2()
'disables the refreshing of the screen to speed up the script
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = "E:\Cascade\RunSheet-Heath Edition\CH54\"
templateName = "CH54_Template"
fileExt = ".xlt"
bookName = ActiveWorkbook.Name
Debug.Print (bookName)
filePath = directory & templateName & fileExt
Dim wb As Workbook
'opens the template
Set wb = Workbooks.Open(filePath)
'copy over the template sheet
Sheets(1).Copy _
Before:=Workbooks(bookName).Worksheets(1)
'closes the template
wb.Close
' renames the newly created sheet
Sheets(1).Name = "RunSheet"
'Resume updating the screen
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I am about to try to select a range and try copying that over, but seems odd that this is happening anyway.
It seems like a weird cache thing to me. as if the Front end excel interface shows the true data but for whatever reason the VBA script pulls from an older version of the template file.
I have saved both workbooks and closed them, even restarted the computer, the template is as it should be. Not what it is currently pasting. What it is pasting is not even saved on the computer as a file anymore, nor is it opened when I go line by line step through in the code. The correct file is being opened.
I should note that when I open up the template but just clicking the file on Windows the excel header is CH54_Template1.xlt, and not just "CH54_Template.xlt" as the file is named.
I start with one workbook open:
I run the code which opens:
this file
The code finished and I am left with
which is from something I had made a month or so ago and since deleted.

Related

code added to a xlsm worksheet while saving in VBA keeps diapearing

I build a xlsm file that takes a database of a few hundred lines as input, processes them and outputs a few seperate .xlsm files, each containing some rearanged part of the input.
I would like to add a simple "Worksheet_BeforeDoubleClick" sub to each of the generated output files.
when working through the input, at the end of the for loop, I do the following:
Dim numLines As Integer
Set CodeCopy = ThisWorkbook.VBProject.VBComponents("Module2").CodeModule
numLines = CodeCopy.CountOfLines
NewBook.VBProject.VBComponents("Sheet1").CodeModule.AddFromString CodeCopy.Lines(1, numLines)
AccessMode:=xlExclusive, _
ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
NewBook.Saved = False
NewBook.SaveAs Filename:="cw_" & cw & "_" & myVendors(N), _
ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges, _
FileFormat:=52
NewBook.Close
If I add a break before the "NewBook.Close", everything seems to work. The split file is shown as a seperate project and "Sheet2" contains the required code.
If I let the sub resume, the file is closed but if I reopen it manually the code is gone.
If I instead stop at the "NewBook.Close" and save the split file seperately the code remains in the file.
I have no idea why your code is gone after save - however, I generally think writing code using the VBE is not a good idea. And you need to allow this in the Trust Center Settings where it is usually disabled (for good reasons).
It is much easier to put the code into a template worksheet that sits in your workbook where your code sits. When create the new workbook, you simply copy this template sheet into it and voilà, all the code is copied with it. You can also put some formatting into the template - no need to do the formatting via code.
If you want, you can completely hide the template sheet - you just have to temporarily set it to visible before you copy it (use Application.ScreenUpdating = False to prevent flicker).
If you use the Copy-method of a worksheet without parameters, Excel will create a new Workbook with only this sheet. Of course, you can also create the new Workbook and use the Copy-method with Before or After-parameter.
Const TemplateSheetName = "Template"
With ThisWorkbook.Sheets(TemplateSheetName)
Application.ScreenUpdating = False
Dim saveVisibility As Long
saveVisibility = .Visible§
.Visible = xlSheetVisible
.Copy
.Visible = saveVisibility
Application.ScreenUpdating = True
End With
Dim newWb As Workbook, newWS As Worksheet
Set newWb = Workbooks(Workbooks.Count)
Set newWS = newWb.Sheets(TemplateSheetName)
newWS.Name = "MyNewDataSheet" ' You should assign a new name to the sheet

Using VBA in Excel to force save in directory

I have a huge Excel spreadsheet that I need to allow access to a large set of users so they can manipulate it for their customers, but I don't want them to be able to overwrite the original file (a variable easily set in Excel) or save their file outside the current folder - so I want to force them in a "saveas" mode, and force the file to be saved in that folder. Otherwise, they won't be able to save. I'm not much of a VBA person, and I've found a lot of examples that may work, but nothing seems to be exactly what I need or maybe I'm not smart enough to figure it out. I found this code, but I'm not sure it FORCES the issue. Help?
I've tried to manage this in GPOs but everything seems to give them access to download the folder and save in other places.
Sub ExampleToSaveWorkbookSet()
Dim wkb As Workbook
'Adding New Workbook
Set wkb = Workbooks.Add
'Saving the Workbook
wkb.SaveAs "C:\WorkbookName.xls"
'OR
'wkb.SaveAs Filename:="C:\WorkbookName1.xls"
End Sub
Expected output is the amended Excel file saved in the original directory with a different name, or not at all.
Here's a macro that runs on open and immediately saves as .xlsx to a user location you can specify. Unfortunately the original needs to be .xlsm to store a macro.
This macro is to be located in the "ThisWorkbook" object. It will exit before making a copy when you open the workbook.
Private Sub Workbook_Open()
Dim wb As Workbook
Set wb = ActiveWorkbook
vWbName = wb.Name
vUserProf = Environ("USERPROFILE")
vx = InStr(1, vUserProf, "Users\")
If "<Use your own profileID>" = Mid(vUserProf, vx + 6) Then Exit Sub
vDir = vUserProf & "\Downloads\"
vWbName = Left(vWbName, Len(vWbName) - 5) & ".xlsx"
wb.SaveAs vDir & vWbName, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
MsgBox "You are now using a copy of the original"
End Sub

VBA code to copy range of data from closed file in SharePoint to open file

This question has been asked in different chats and I have tried to incorporate the varying solutions but without success. I am attempting to open a SharePoint file and copy data from the file to the open file that has the macro within. The below solution is the last attempt I tried that did open the SharePoint file but would not select the desired range. A Run-time error '9' Subscript out of range was returned. If it makes it easier, my goal is to simply copy the entire sheet from the closed file into the open file. Code used is below. Any direction and or suggestions are appreciated.
Private Sub CommandButton1_Click()
Dim x As Workbook
Dim y As Workbook
Set x = Workbooks.Open("http://employee.xtra.net/sites/Ops/Support%20Launch%20Docs/ep_timing_wb_report.xlsx")
Set y = ThisWorkbook
x.Sheets("ep_timing_wb_report 1").Range("A:AA").Copy
y.Sheets("ep_timing_wb_report").Range("A:AA").PasteSpecial
x.close
End Sub
Bruce was correct with the recommendation of simply using a Hyperlink in the cell. This was attempted earlier but I must not have linked properly.
See if this works for you (comments included).
Sub OpenAndCloseWBFromSharePointFolder()
'If nobody has the file checked out
If Workbooks.CanCheckOut("http://excel-pc:43231/Shared Documents/ExcelList.xlsb") = True Then
Application.DisplayAlerts = False
'Open the file on the SharePoint server
Workbooks.Open Filename:="http://excel-pc:43231/Shared Documents/ExcelList.xlsb", UpdateLinks:=xlUpdateLinksNever
'Close the workbook
Workbooks("ExcelList.xlsb").Close
Application.DisplayAlerts = True
Else
Application.DisplayAlerts = False
'Open the File to check if you already have it checked out
Workbooks.Open Filename:="http://excel-pc:43231/Shared Documents/ExcelList.xlsb", UpdateLinks:=xlUpdateLinksNever
'See if doc can be checked in
If Application.Workbooks("ExcelList.xlsb").CanCheckIn Then
'Check In, Save and Close
Application.Workbooks("ExcelList.xlsb").CheckIn SaveChanges:=True, Comments:="Checked-In before Delete"
'Open the file again
Workbooks.Open Filename:="http://excel-pc:43231/Shared Documents/ExcelList.xlsb"
'Close the workbook
Workbooks("ExcelList.xlsb").Close
End If
End If
End Sub

Designate Excel Data Connection ReadOnly

I have an Excel file with a data connection to another Excel source which is referenced by several other reports. The data connection should be read only, but I cannot seem to setup the properties to do so - whenever the source file is open somewhere else, the data connection attempts to open the source as read-write. I have tried to enter ReadOnly=0,ReadOnly=TRUE, and ReadOnly=1, but nothing seems to be effective.
When the source file opens, it seems to interrupt my macro which executes as a timer. The connection string for my data connection is (with substituted paths):
DSN=Excel Files;DBQ="Source File Path";DefaultDir="Directory Path";DriverId=1046;MaxBufferSize=2048;PageTimeout=5;
I copy the workbooks from the source into the workbook I use them in. For this i use the following code (with ReadOnly:=True):
'Open workbook
Application.DisplayAlerts = False
Application.EnableEvents = False
Workbooks.Open ("location"), UpdateLinks:=0, ReadOnly:=True
'Copy worksheet
Workbooks(sourceWorkbook).Worksheets(sourceSheet).Copy _
after:=Workbooks(destinationWorkbook).Worksheets(Workbooks(destinationWorkbook).Worksheets.Count)
'Close source workbook
Workbooks(sourceWorkbook).Close
Application.EnableEvents = True
Application.DisplayAlerts = True
Hope that helps

Excel Macro generated file copy keeps links to original files

I have sales global sales data in very large files which I need to filter by country and product and then analyze. Since I will need to perform this same analysis over and over again with different country/product combinations I am trying to do this with a macro.
This is what the macro does:
Open the source files with global data;
Filters the data;
Copies it and pastes it into a workbook which houses the macro;
Recalculates and refreshes the workbook and;
Saves a copy of the file to another folder.
The macro appears to run fine and the files are being saved, however I am running into 2 problems on steps 4 and 5:
The pivot tables do not seem to be refreshing - this may be because the second problem:
All pivot tables in the saved copy still refer to the original file
I'd prefer to fix both problems by generating the copied file without links, but I'm also open to any bandaids that might allow me to force the copied file to link to itself (this doesn't seem to work when I do it manually).
I have the full code if you want to see it all, but because I suspect the issue is in how I'm saving the file I'll just paste that piece here. Let me know if you need to see another part of the macro. Any help would be much appreciated, thanks in advance.
Save Function:
Public Sub SaveAsCopy(filePath As String)
Dim updateStatus As Boolean
'Check current status of Alerts
updateStatus = Application.DisplayAlerts
'Turn off alerts
Application.DisplayAlerts = False
ThisWorkbook.Sheets.Copy 'creates new workbook without macros"
'The New workbook copy is now the Active workbook
'Delete Control Sheet
ActiveWorkbook.Sheets(1).Delete
'Save Macro free version and close
ActiveWorkbook.SaveAs Filename:=filePath, FileFormat:=51
ActiveWorkbook.Close
'Revert back to origional alert status
Application.DisplayAlerts = updateStatus
End Sub
Function Call:
Call SaveAsCopy(filePath)
Will share the workaround I developed since I didn't get any bites on a more elegant solution:
Public Sub SaveAsCopy(filePath As String)
Dim updateStatus As Boolean
'Check current status of Alerts
updateStatus = Application.DisplayAlerts
'Turn off alerts
Application.DisplayAlerts = False
'Hide Control Sheet
ActiveWorkbook.Sheets(1).Visible = False
'Save Macro free version and close
ActiveWorkbook.SaveAs Filename:=filePath, FileFormat:=52
'Unhide
ActiveWorkbook.Sheets(1).Visible = True
'Revert back to original alert status
Application.DisplayAlerts = updateStatus
End Sub
At the end of the parent function I close the current file, reopen the original, and loop through the new workbooks to remove macros.

Resources