How can I save an Excel backup in SharePoint? - vba

How can I save an Excel backup in SharePoint?
To access the share point folder I need a username and password.
Attached capture of the code and the error that jumps to me.
I leave the code here below.
ServerShare = "https://mycom.sharepoint.com/sites/Backupvehculo/Shared%20Documents/General/Copia/"
UserName = "xxxx"
password = "xxxx"
Set NetworkObject = CreateObject("WScript.Network")
NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, password
nombrearchivo = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 5) & VBA.Format(VBA.Now, "_dd-mm-yyyy-hh:mm:ss")
ActiveWorkbook.SaveAs filename:= _
"https://mycom.sharepoint.com/sites/Backupvehculo/Shared%20Documents/General/Copia/" & nombrearchivo & ".xlsm" _
, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
'Set FSO = Nothing
Set NetworkObject = Nothing

I did this almost 10 years ago. Not sure it still works, but you can try it.
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

Related

Bringing data from other workbooks - goal not accomplished in nested if

I have this code in which I am bringing data from several workbooks into one. The data of each workbook needs to be added into a specific range depending on the source. To do this I nested some IFs with the partial name of the file as condition and giving the action of sending the values to the desired range, but when I run the code it only opens all the workbooks without performing any action. I already did some research and did not find anything to help me with my problem
Sub Update_Database()
Dim directory As String
Dim fileName As String
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
directory = .SelectedItems(1)
Err.Clear
End With
fileName = Dir(directory & "\", vbReadOnly)
Dim mwb As Workbook
Set mwb = Workbooks("OEE_Database_Final.xlsm")
Do While fileName <> ""
On Error GoTo ProcExit
With Workbooks.Open(fileName:=directory & "\" & fileName, UpdateLinks:=False, ReadOnly:=True)
If (fileName = "NOM*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O9:Z290").Value = mwb.Sheets("Database").Range("O9:Z290")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "SZE*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O291:Z537").Value = mwb.Sheets("Database").Range("O291:Z537")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "VEC*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O538:Z600").Value = mwb.Sheets("Database").Range("O538:Z600")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "KAY*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O601:Z809").Value = mwb.Sheets("Database").Range("O601:Z809")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "BBL*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O810:Z952").Value = mwb.Sheets("Database").Range("O810:Z952")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "POG*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O953:Z1037").Value = mwb.Sheets("Database").Range("O953:Z1037")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "SC1*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O1038:Z1159").Value = mwb.Sheets("Database").Range("O1038:Z1159")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "SC2*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O1160:Z1200").Value = mwb.Sheets("Database").Range("O1160:Z1200")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "SLP*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O1201:Z1263").Value = mwb.Sheets("Database").Range("O1201:Z1263")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "UIT*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O1264:Z1348").Value = mwb.Sheets("Database").Range("O1264:Z1348")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "ANE*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O1349:Z1823").Value = mwb.Sheets("Database").Range("O1349:Z1823")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "HAL*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O1824:Z2077").Value = mwb.Sheets("Database").Range("O1824:Z2077")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "SHX*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O2078:Z2242").Value = mwb.Sheets("Database").Range("O2078:Z2242")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "BAY*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O2243:Z2415").Value = mwb.Sheets("Database").Range("O2243:Z2415")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "TAM*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O2416:Z2522").Value = mwb.Sheets("Database").Range("O2416:Z2522")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "PUC*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O2523:Z2607").Value = mwb.Sheets("Database").Range("O2523:Z2607")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "JOF*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O2608:Z2648").Value = mwb.Sheets("Database").Range("O2608:Z2648")
ActiveWorkbook.Close SaveChanges:=False
ElseIf (fileName = "MAV*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O2649:Z2945").Value = mwb.Sheets("Database").Range("O2649:Z2945")
ActiveWorkbook.Close SaveChanges:=False
End If
End With
fileName = Dir
Loop
Application.ScreenUpdating = True
ProcExit:
Exit Sub
End Sub
You can "cheat" a little to get away with Select Case.
In order to use the Like with Select, you use Select Case True and then nest your scenraios using Like and wild card *.
code
With Workbooks.Open(Filename:=directory & "\" & Filename, UpdateLinks:=False, ReadOnly:=True)
Select Case True
Case Filename Like "NOM*.xlsx"
Case Filename Like "SZE*.xlsx"
Case Filename Like "VEC*.xlsx"
Case Filename Like "KAY*.xlsx"
Case Filename Like "BBL*.xlsx"
' put all other scenarios down here....
End Select
End With
Note: if all your files you are trying t check are excel files, so you don't need to add the .xlsx extension, just use NOM*, SZE*, etc.
Given the snippet
With Workbooks.Open(fileName:=directory & "\" & fileName, UpdateLinks:=False, ReadOnly:=True)
If (fileName = "NOM*.xlsx") Then
ActiveWorkbook.Sheets("Database").Range("O9:Z290").Value = mwb.Sheets("Database").Range("O9:Z290")
ActiveWorkbook.Close SaveChanges:=False
End If
End With
you're opening a file, writing some values from mbw.Sheets("Database") to it and then close the just modified file without saving.
From your comment it seems your intention is to do the opposite:
Dim mwb As Workbook
Set mwb = Workbooks("OEE_Database_Final.xlsm")
Dim Ws As Worksheet
Set Ws = mwb.Sheets("Database")
Do While Filename <> ""
On Error GoTo ProcExit
With Workbooks.Open(Filename:=directory & "\" & Filename, UpdateLinks:=False, ReadOnly:=True)
Select Case True
Case Filename Like "NOM*.xlsx"
Ws.Range("O9:Z290").Value = .Sheets("Database").Range("O9:Z290").Value
.Close SaveChanges:=False
Case Filename Like "SZE*.xlsx"
' Code for this case
' Other cases...
Case Else
' Put code here that is executed if none of the previous names has been matched
' or remove 'Case Else' if you don't want anything to happen then
End Select
End With
Filename = Dir
Loop
Some things to note:
I've implemented the suggestion from Shai Rado's answer to make use of the Like operator in a Select Case structure
I've assigned a new Worksheet variable as such Set Ws = mwb.Sheets("Database") - this shortens the lines and makes it easier to refer to a different sheet, should requirements change (one change as opposed to ~20 changes)
The With block now is actually taken advantage of. When you do With Workbooks.Open, VBA provides you with an implicit reference to that workbook. So there is no need to refer to ActiveWorkbook. A simple . is enough. Also it removes that brittle dependency on having the right workbook active at the right time. (Imagine what happens if for whatever reason the ActiveWorkbook changes half-way through your macro... Not a likely scenario, I'll give you that.)

Excel file not saving to the correct path

I wrote the following procedure to save my file to a network path:
Sub Save_Book()
Dim savePATH As String
savePATH = "\\ftl-store\Departments\HR\HR Reports and Metrics\LOA Reports\BRT Reports"
Application.ScreenUpdating = True
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=savePATH & sFile, FileFormat:=51
Application.DisplayAlerts = False
End Sub
However, my procedure is not working correctly. Its saving the file to the path, but the correct path. It saves the file to here: \\ftl-store\Departments\HR\HR Reports and Metrics\LOA Reports\BRT Reports" Thus missing the destination folder.
Instead of saving the file to the path it takes this part:
BRT Reports
and shows as part of my file name when it saves.
Any help will be appreciated.
You must add the trailing backslash:
Sub Save_Book()
Dim savePATH As String
savePATH = "\\ftl-store\Departments\HR\HR Reports and Metrics\LOA Reports\BRT Reports\"
Application.ScreenUpdating = True
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=savePATH & sFile, FileFormat:=51
Application.DisplayAlerts = False
End Sub

Excel VBA: How to dismiss password boxes for linked files in Macro

I am trying to dismiss pop up password boxes while my macro is running, each file is password protected which i have code for to unlock these however the files also are linked to other password protected files that excel prompts me for a password, instead of clicking cancel every time one of these boxes pops up is there a way to dismiss the password boxes in the macro?
Here is my current code:
Sub OpenCurrentGBP()
cdirectory = Range("E5").Value
Mdirectory = Range("E6").Value
cGap = Range("E11").Value
cEVE = Range("E12").Value
cHedge = Range("E13").Value
cVarFile = Range("E16").Value
cGapMovements = Range("E17").Value
cQRMCheck = Range("E18").Value
GapPwd = Range("E42").Value
EVEPwd = Range("E43").Value
HedgePwd = Range("E44").Value
EurogapPwd = Range("E45").Value
EuroEVEPwd = Range("E46").Value
VarPwd = Range("E47").Value
MovPwd = Range("E48").Value
Application.DisplayAlerts = False
Call OpenFile(cdirectory, cGapMovements, MovPwd)
Call OpenFile(cdirectory, cGap, GapPwd)
Call OpenFile(cdirectory, cEVE, EVEPwd)
Call OpenFile(cdirectory, cHedge, HedgePwd)
Call OpenFile(cdirectory, cVarFile, VarPwd)
Call OpenFile(cdirectory, cQRMCheck)
Application.DisplayAlerts = True
End Sub
The OpenFile Macro is as follows:
Sub OpenFile(Directory, File, Optional Pass)
On Error GoTo Failure
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
If IsMissing(Pass) = 0 Then
Workbooks.Open Filename:= _
Directory & "\" & File, Notify:=False, Password:=Pass
Else
Workbooks.Open Filename:= _
Directory & "\" & File, Notify:=False
End If
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Exit Sub
Failure: MsgBox (File & " could not be opened")
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
End Sub
Inside the subs you call (Next time you should show them here too) to open the protected Workbooks you need to use the Workbooks.open statment and I have an example of my own codes that I am using to open workbooks with password:
Workbooks.Open Filename:=tmp_file_p, Password:="7399"
tmp_file_p is a string variable with the path and the name of the workbook.

How to retain the original workbook during SaveAs

I am trying to retain the original workbook opened and close all other saved(saved with different names) files without reopening. I am doing the SaveAs through a button click. Any suggestions on this?
sub save()
Application.DisplayAlerts= False
FileName1 = Range("D4")
ActiveWorkbook.SaveCopyAs FileName:="C:\Users\felonj\Desktop\list\" & FileName1 & "-" & "Audit checklist" & ".xlsm"
MsgBox "File Saved successfully!", , "Save"
Application.DisplayAlerts = True
End sub
If I have to use your code, try something like this:
Option Explicit
Sub save()
Dim obj_wb As Object
Set obj_wb = ThisWorkbook
Application.DisplayAlerts = False
ActiveWorkbook.SaveCopyAs Filename:=ActiveWorkbook.Path & "Audit checklist" & ".xlsm"
MsgBox "File Saved successfully!", , "Save"
Debug.Print obj_wb.Name
Application.DisplayAlerts = True
Set obj_wb = Nothing
End Sub
obj_wb is the old file, accessible through this variable. Probably it is a good idea to use "ThisWorkbook" in stead of "ActiveWorkbook". Or to refer it always as a variable and not to use any of those at all.

Read closed .xlsm files as xml files to pull data

I am a new programmer and I am trying to find a way to extract one range of data from multiple workbooks and copy them into a master file. I have already wrote the code to do this below, but the problem that I am having is that my code physically opens the xlsm files > copies the data > then goes back into the master file to paste. Since this is being done to thousands of files at once, it takes hours to complete. My boss told me there is a way to copy the data from the xlsm files without having the code actually open the file if it is read as xml or as a .txt file. I have searched online for this, but cannot find anything on how this would be done. Any help would be greatly appreciated.
The code I have that physically opens the workbooks:
Option Explicit
Sub ReadDataFromCloseFile()
On Error GoTo ErrHandler
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim FileType As String
Dim FilePath As String
FileType = "*.xlsm*" 'The file type to search for
FilePath = "C:\Users\hasib\xlsm's\" 'The folder to search
Dim src As Workbook
Dim OutputCol As Variant
Dim Curr_File As Variant
OutputCol = 9 'The first row of the active sheet to start writing to
Curr_File = Dir(FilePath & FileType)
Do Until Curr_File = ""
' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
Set src = Workbooks.Open(FilePath & Curr_File, True, True)
Sheets("Reporting").Range("I7:I750").Copy
Workbooks("Master.xlsm").Activate
Sheets("Sheet2").Select
Sheets("Sheet2").Cells(4, OutputCol).Select
ActiveCell.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Application.CutCopyMode = False
OutputCol = OutputCol + 1
' CLOSE THE SOURCE FILE.
src.Close False ' FALSE - DON'T SAVE THE SOURCE FILE.
Curr_File = Dir
Loop
Set src = Nothing
Application.EnableEvents = True
Application.ScreenUpdating = True
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
I found out that there is a formula you can use in a cell that will pull in data from a closed workbook. If you type ='folderpath[filename]Sheetname'Cell into a cell it will automatically pull in that information. Using this logic I created the below to loop through all my files and paste data into my workbook from the files being called:
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.InitialFileName = "c:\"
fd.InitialView = msoFileDialogViewList
fd.AllowMultiSelect = True
FileChosen = fd.Show
FilePath = fd.SelectedItems(1)
FolderPath = Left(FilePath, InStrRev(FilePath, "\"))
If FileChosen = -1 Then
'open each of the files chosen
For c = 1 To fd.SelectedItems.count
FileName = Dir(fd.SelectedItems(c))
ThisWorkbook.Sheets("Batch Results").Cells(OutputRow, OutputCol).Formula = "='" & FolderPath & "[" & FileName & "]Reporting'!$I7"
OutputCol = OutputCol + 1
Next c
End If
ThisWorkbook.Sheets("Batch Results").Select
Cells(1, OutputCol).Select
EndColumn = Split(ActiveCell(1).Address(1, 0), "$")(0)
RangeName = ("A1:" & EndColumn & "1")
Range(RangeName).Select
Selection.AutoFill Destination:=Range("A1:" & EndColumn & "558"), Type:=xlFillDefualt