Connecting to Sharepoint File System using VBA - vba

Can someone help explain why when trying to save or copy files over to a file structure that is part of a SharePoint site the code only seems to work if I use the SaveAs code once everytime I log on to my network
The code also works on other excel spreadsheets
If Dir("//teamspace.healthcare.siemens.com/content/90002613/Documents/" & Filename & "", vbDirectory) = "" Then
MkDir ("//teamspace.healthcare.siemens.com/content/90002613/Documents/" & Filename & "")
Else
The code I need to run once on logon is
With ActiveWorkbook
Application.ActiveWorkbook.SaveAs Filename:="https://teamspace.healthcare.siemens.com/content/90002613/Documents/Budget_Presentations/SavedFileName.xlsm"
Application.ActiveWorkbook.Close False
End With
I have tried multiple things, like using different directories, turning the slashes round, using variables. Nothing seems to work, even though exact same code has worked multiple times on a different spreadsheet
Thank You

If you are going to save it as a macro enabled workbook, then you need to explicitly tell the SaveAs command that. Like this:
Application.ActiveWorkbook.SaveAs Filename:="https://teamspace.healthcare.siemens.com/content/90002613/Documents/Budget_Presentations/SavedFileName.xlsm", XlFileFormat:=xlOpenXMLWorkbookMacroEnabled

Related

Excel VBA: SaveAs, then killing old file has permission error

I have Excel VBA code, which I have distributed, to produce some reports. The code has errors, and I have now fixed them. I want to update the end users.
Assume that the code is in a macro workbook "software.xlsm", as is any data that they have entered.
What I have done is to create "software v1.0.1.xlsm". It checks for the presence of "software.xlsm" and copies all the data and parameters from it to itself. It then renames "software.xlsm" as "software v1.0.0.xlsm.old", and saves itself as "software.xlsm". At this point, Excel is quite happy that this is the new name for the workbook.
All that remains is to delete the "updater". But this is where I run into permission errors - Excel won't let me kill it. It is not in use anywhere else, and it seems as if Excel isn't letting go of the original file name.
This is my code:
set newWb = ActiveWorkbook
thisName = newWb.FullName ' get full name of updater
newWb.SaveAs newWb.Path & "\software.xlsm" ' save updater as code file
Kill thisName ' delete updater <!! FAILS
I'm tearing my hair out here. I have checked here an online, and what I am doing should work - but it doesn't!
Thanks.
EDIT: I should mention that I have also tried SetAttr on the file, which also has no effect.
EDIT2: I am not sure I am being clear about what I want to do. I want to get rid of the updater once it has run, so as to not confuse the users. So I used "SaveAs" to save the updater with a new name, which left TWO files on the disk, and ONE file open in Excel. I am then trying to kill / delete the file that IS NO LONGER open in Excel (i.e. the updater before I saved it with a new name).
newWb.Close (you have to close it before you can delete it)
You can also try setting the variable to nothing.
Set newWb = Nothing
The error you are encountering is because you are trying to access the FullName of the workbook which has since changed after the SaveAs. For example. If I have a workbook with the FullName "SomeFilePath.foo" and I do a SaveAs with FullName & ".old" the FullName is now "SomeFilePath.foo.old".
This makes sense, but the part you are getting tripped up on is your thisname variable. For example:
Dim thisName as String
thisName = ActiveWorkbook.FullName
Debug.Print thisName ' E.G "SomeFilePath.Foo"
ActiveWorkbook.SaveAs ActiveWorkbook.FullName & ".old"
Debug.Print thisname ' Still "SomeFilePath.Foo"
The workbook by the old name simply doesn't exist anymore. It has been changed to the new name.
How do we fix this? You could find the new name and still Kill it, but you dont see Kill often for a reason, it is a bad practice.
The ideal would be to properly host, and reference, your workbook. For example:
thisName = thisWorkbook.FullName
thisWorkbook.SaveAs thisWorkbook.FullName & ".old"
thisWorkbook.Close(False)
We are almost there. We are saving the workbook and closing the current workbook, but this isnt actually what we want. What we need instead is:
thisWorkbook.SaveCopyAs thisWorkbook.FullName & ".old"
thisWorkbook.Close(False)
Instead of changing the FilePath of the updating workbook, just make a copy of it. Not only is it cleaner, but it allows us to not have to worry about the funky things that can happen when we mess with a file when it has code currently running.
Note though, you will want to chance the output file path to the path you actually intend. The ".old" is purely for example. Likewise, ThisWorkbook.Close(False) isn't ideal, but if you must close immediately after finishing then this will work best.
TLDR: The permission denied error is caused by referencing a workbook, by name, that no longer exists within the processes.

Excel VBA Run Time Error 1004 "Application-Defined or Object-Defined Error"

I am writing a program that currently, when the user clicks "OK", saves the current file, copies certain values in the file; then pastes the values to a different file. Then both files close. My problem is that it gives me an error:
Run Time Error: 'Application-Defined or Object Defined Error'
It highlights this line:
ThisWorkbook.Worksheets("data").Range("C31", Range("C106").End (xlToRight)).Copy
I separated this line and the one right after it to test it alone and it worked like I wanted to. I tested the rest of the program without those two lines and it worked like I expected it to.
I tried to limit it to just copying one cell and it worked.
I made sure that the name of the sheet was correct.
I tried to just copy one row:
Range("C31", range("C31").End(xlToRight))
it still did not work and I came across the same error message.
I want to say I referenced something wrong but I don't see it.
Any reply at all would be helpful, Thank you.
P.S. I am sorry for redundancy in the code, I don't use "Dim" as much as I should.
Sub Button425_Click()
Dim FName As String
Dim FPath As String
Dim yourmsg As String
Dim testmsg As String
yourmsg = "Are you sure that you want to save and exit?"
testmsg = MsgBox(yourmsg, vbOKCancel + vbExclamation)
FPath = "I:\a\d\f\daily log recycle\"
FName = Sheets("Sheet1").Range("C3").Text
If testmsg = 1 Then
ThisWorkbook.SaveAs filename:=FPath & "\" & FName
Workbooks.Open ("I:\a\d\f\new daily log 1.xlsm")
ThisWorkbook.Worksheets("data").Range("C31", Range("C31").End(xlToRight)).Copy
Workbooks("new daily log 1.xlsm").Worksheets("data").Range("D31").PasteSpecial xlPasteValues
ThisWorkbook.Worksheets("sheet1").Range("E45").Copy
Workbooks("new daily log 1.xlsm").Worksheets("sheet1").Range("E44").PasteSpecial
Workbooks("new daily log 1.xlsm").Worksheets("sheet1").Range("E45").ClearContents
Workbooks("new daily log 1.xlsm").Save
Workbooks("new daily log 1.xlsm").Close
ThisWorkbook.Saved = True
Application.Quit
Else 'do nothing
End If
End Sub
You're mixing a fully addressed range
ThisWorkbook.Worksheets("data").Range("C31"
with a relatively addressed range
Range("C106").End (xlToRight)
Try
ThisWorkbook.Worksheets("data").Range("C31", ThisWorkbook.Worksheets("data").Range("C106").End (xlToRight))
I see a couple of issues:
FPath = "I:\a\d\f\daily log recycle\"
ThisWorkbook.SaveAs filename:=FPath & "\" & FName
When you attempt to save you will have ...\daily log recycle\\<filename>. Remove one of the backslashes \, I'd suggest removing the one in the .SaveAs line.
Then, with these two lines:
Workbooks.Open ("I:\a\d\f\new daily log 1.xlsm")
ThisWorkbook.Worksheets("data").Range("C31", Range("C31").End(xlToRight)).Copy
The ThisWorkbook probably isn't pointing to the one you think it is. On all the following lines you specify Workbooks("new daily log 1.xlsm")., why don't you replace ThisWorkbook with an explicit Workbooks("...") so you can be 100% certain of which of the two open workbooks you're referencing.
I would also do that for these two lines:
ThisWorkbook.Worksheets("sheet1").Range("E45").Copy
ThisWorkbook.Saved = True
Also, just to be clear, ThisWorkbook.Saved = True tells Excel to not prompt you to save the workbook when you close it, but it doesn't actually save the workbook. If you want to actually save it, you'll need to use .Save, just like you do a couple lines above that for Workbooks("new daily log 1.xlsm").Save.

EXCEL VBA: opening XLSM excel using vba

i cant figure out my error in my codes
If cboUnit.Text = "MARINER" Then
Application.ScreenUpdating = False
Application.Workbooks.Open Filename:=ThisWorkbook.Path & "\UNIT" & "\MARINER"
ThisWorkbook.Activate
Workbooks("TOUKEI DATA REPORT GRAPHING").Close
End If
i just want to open xlsm file which is on the folder unit
but i always got an error:
runtime error '1004'
the file this getting is 'xlsx' extension
If you use something like this, it should at least make debugging simpler. Then substitute the code I've provided with this line:
Application.Workbooks.Open Filename:=ThisWorkbook.Path & "\UNIT" & "\MARINER"
Declare the variables with your other variables. I'm understanding your question to be that "Mariner" is the file name. If it's not, you will need to change the fileNPath.
Dim path As String, fileNPath As String
'add these two values above your code
path = ActiveWorkbook.path
fileNPath = path & "\UNIT\MARINER.xlsm"
Application.Workbooks.Open fileName:=fileNPath 'Change this line
Once you've done this, you can see the values for the file path in debug mode where the version you have won't have a value until the line that isn't working anyway. So this way, you can SEE what is going on before you try to USE it.
note: To have a macro enabled workbook, it must be .xlsm, not .xlsx

Saving an Excel sheet in a current directory with VBA

I have created a sheet in vba Excel. I would like to save it the current directory, but not in absolute path, then, when this is executed somewhere else, there won't be problem.
Can somebody help ?
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path to get a relative file path:
Sub SaveToRelativePath()
Dim relativePath As String
relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.
MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"
This assumes that the sheet you want to save has never been saved and you want to define the file name in code.
If the Path is omitted the file will be saved automaticaly in the current directory.
Try something like this:
ActiveWorkbook.SaveAs "Filename.xslx"
Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:
workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"
Only works if your file structure contains one instance of the text used to replace. YMMV.

How to make Excel VBA Automation Execute for All End Users

I wrote the following code so that when an Excel spreadsheet is closed it will update its name with the current date and time:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If ThisWorkbook.Name = "Name_Last Opened-" & Format(Date, "MM-DD-YYYY") & _
"_" & Format(Time, "HH.MM") & ".xls" Then
Else
ThisWorkbook.SaveAs Filename:="\\C:\... Name_Last Opened-" & _
Format(Date, "MM-DD-YYYY") & "_" & Format(Time, "HH.MM") & ".xls"
FName = Sheets("Name").Range("D1").Text
Kill FName
End If
End Sub
Private Sub Workbook_Open()
Range("A1").Select
ActiveCell.FormulaR1C1 = ThisWorkbook.Name
End Sub
Additionally, the code is located within VBAProject(Name of file), under MS Excel Object - ThisWorkbook.
This code works perfectly for me or the workstation that it was created on; however, it does not execute for anyone who opens it on their worstation. Would anyone know how to get the code to execute whenever the spreadsheet is opened and closed from any computer, not just mine?
Thank you,
DFM
It's possible that Excel's security settings aren't allowing other people's computers to run the script that could be interpreted as risky malware. Perhaps you changed your security settings so long ago that you forgot about it. See if you can modify another user's security settings to see if that will make the macro execute on the workbook close.
"Would anyone know how to get the code to execute whenever the spreadsheet is opened and closed from any computer, not just mine?"
I don't think it can be done with 100% certainty unless you can ensure that every possible user will have macro security set such that your macro can execute.
Assuming you can get past that one, you should perhaps check that the users all have the worksheet in the same hard-coded path on C:\ that you seem to be using. What happens if they open the workbook from a different location?
Also:
FName = Sheets("Name").Range("D1").Text
is getting a value from one place and
Range("A1").Select
ActiveCell.FormulaR1C1 = ThisWorkbook.Name
is putting it in another.
I think I'd try something like the following (which assumes from your code that you actually only want to change the file name if it has not changed since the minute of the current time changed):
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim dateTime As String
Dim oldPath As String
Dim newPath As String
dateTime = Format(Now, "MM-DD-YYYY_HH.MM") ' Format the while thing in one string - once
With ThisWorkbook
oldPath = .FullName ' what is it called now, and where did it come from?
newPath = .Path & "\" & "Name_Last Opened-" & dateTime & ".xls" ' what should it be called now?
If oldPath <> newPath Then ' only do something if not saved in last minute - is that what you really want?
.SaveAs Filename:=newPath
Kill oldPath
End If
End With
End Sub
Date() function needs administrator access to run.. so if your user is a non admin, then it will fail. Instead use now(). Most of the times this is some thing which we usually forget as we(people developing the tool) have admin access over our PC's
Fundamentally, you cannot ensure that all users will a) have a macro security setting of low or medium, and b) if set to medium, enable them when the file is opened.
Creating your own certificate would seem like the obvious answer, but in practice I find that the resultant messages and warnings are even more confusing/frightening for some end users, leading to much the same situation as with macro security. Third-party certificates avoid this, but are $$$ and almost surely overkill for an Excel workbook in a corporate environment.
What I've done where I need users to have VBA enabled is to set all sheets to xlveryhidden on save, except a custom locked sheet that only has a note saying macros must be enabled and a brief guide on how to do this. This sheet is hidden and the others restored by the workbook's workbook_open procedure, something that of course will not fire if VBA is disabled.