Why i can connect to a sharepoint site with vba from one spreadsheet but not another - vba

I have an odd issue where I can connect and upload files to a sharepoint site using a vba script, however using practically the same vba script from another spreadsheet and uploading to the same sharepoint site I can't connect and upload files.
The weird thing with the vba script that doesn't work is that if I add the below code to it before the rest of the script, the rest of the script works.
xPath= "https://teamspace.healthcare.siemens.com/content/90002613/Documents/"
With ActiveWorkbook
Application.ActiveWorkbook.SaveAs Filename:=xPath & Name & ".xlsm"
Application.ActiveWorkbook.Close False
End With
No idea why but xPath is a valid file path when using the SaveAs command, but when I use the same path or variant of it with the "Dir" tag it doesn't work and either give me a error code "Runtime 52 Bad File name or number" or "Runtime 76 path not found". Please can someone help with this, I have been trying everything I can think of for about the last 2 days
Thanks
Edit :
this is the code that works in one of the spreadsheets
If Dir("//teamspace.healthcare.siemens.com/content/90002613/Documents/GB_Invivo_RSM/" & xWs.Name & "", vbDirectory) = "" Then
MkDir ("//teamspace.healthcare.siemens.com/content/90002613/Documents/GB_Invivo_RSM/" & xWs.Name & "")
Else
End If
With ActiveWorkbook
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\GB_RSM_P" & Format(LDate, "mm") & "FY" & Format(LDate, "yyyy") & " " & xWs.Name & ".xlsx"
End With
The code in the 2nd spreadsheet wont work unless I put another SaveAs() before all of this, and save a dummy spreadsheet, then have to delete it after, because obviously I don't want it there. I can't understand why the same code would work from one spreadsheet and not another, and also its almost like the saveAs() is creating a connection or something, but this wasn't needed in the 1st spreadsheet

If your URL is "https://teamspace.healthcare.siemens.com/content/90002613/Documents/" then you should be able to use Dir() as shown below:
Sub TestWebDAVDir()
Const MY_PATH As String = "\\teamspace.healthcare.siemens.com\content\90002613\Documents\"
Dim f
f = Dir(MY_PATH & "*")
Do While Len(f) > 0
Debug.Print f
f = Dir()
Loop
End Sub

Related

Word - Prevent SaveAs2 (VBA) from overwriting

Somewhere on the internet I found this code to easily save a .docx file out of a .dotx file into the desired folder:
Sub SaveFileInTheCorrectDirectory()
ActiveDocument.SaveAs2 "[the correct directory, put in manually by me in the VBA code]" & InputBox("Type the desired file name", "Save As")
End Sub
However, this code automatically overwrites an already existing file with the same name (and in the same directory, of course). I've tried looking for code to fix this, and found a few suggestions:
Trying to save word file, from excel vba, without over-writing any existing files
https://answers.microsoft.com/en-us/msoffice/forum/all/vba-macro-saveas-overights-exsiting-file-without/e6fce3b1-ee72-498d-8fe5-fbc3e0cdbf23
http://computer-programming-forum.com/1-vba/2fb545278f4311ff.htm
https://groups.google.com/g/microsoft.public.word.vba.customization/c/Q4W2CK4gQOg?pli=1
But I can't figure out how to implement them...
Could someone be so kind to assist me?
Thanks!
PS Is there added value to use "SaveAs2" instead of "SaveAs" or the other way around?
That's as simple as:
Dim StrName as String
StrName = InputBox("Type the desired file name", "Save As")
If Trim(StrName) = "" then Exit Sub
If Dir(StrPath & StrName & ".docx") = "" Then ActiveDocument.SaveAs2 StrPath & StrName & ".docx"
where StrPath & StrName are the path & name, respectively.
Note: I haven't added any code for what to do if the file exists because you haven't said what you want to do in that case. Post a new question if you need help with that.

VBA SaveCopy function + lose a worksheet

I created an Excel 2016-based template, which the user can fill and create a work form based on it. User inserts an unique ID and with basic INDEX&MATCH formulas some ID-related parameters are being fetched from separate worksheet a. The work form is created with VBA-macro using SaveCopyAs method.
After the parameters have been fetched and VBA is launched to create the work form the ID will not change anymore. Thus, I don't need the whole worksheet a anymore and would like to drop it to keep the work form more lightweight. I'm capable of retaining the fetched parameters, so this is not a problem.
I would NOT want the user to have to re-open the form every single time a work form is created, so I don't want the VBA to remove worksheet a from the template itself, as even though the user can't save changes to the template, (s)he would have to re-open the template file every time a work form has to be created.
Any idea if something could be done? Might it be possible to somehow run SaveCopyAs or similar method, but drop the worksheet a at the same time from the new target file? Having INDEX&MATCH formula fetch the needed information from another workbook would theoretically work but to my knowledge requires the other workbook to be open at all times which will undoubtedly start to cause unnecessary issues.
My current VBA for work form creating is something like this:
Sub Save_copy()
Dim FileName As String
With ActiveWorkbook
[H3] = Format(Now, "dd.mm.yy_hhmm")
Range("H2").Value = Range("H1").Value
FileName = "SERVICE " & _
Range("H1").Value & _
" - " & Format(Now, "dd.mm.yy") & _
"_" & Format(Now, "hhmm") & _
"." & Right(.Name, Len(.Name) - InStrRev(.Name, "."))
.SaveCopyAs "G:\SERVICE" & "\" & FileName
End With
Call Reset
End Sub
If I understood you properly try something like this ("air-coded" so there may be typos):
Sub Save_copy()
Dim FileName As String
With ActiveWorkbook
[H3] = Format(Now, "dd.mm.yy_hhmm")
Range("H2").Value = Range("H1").Value
FileName = "SERVICE " & _
Range("H1").Value & _
" - " & Format(Now, "dd.mm.yy") & _
"_" & Format(Now, "hhmm") & _
"." & Right(.Name, Len(.Name) - InStrRev(.Name, "."))
.SaveCopyAs "G:\SERVICE\" & FileName
End With
Dim newWorkbook As Excel.Workbook
Set newWorkbook = Workbooks.Open("G:\service\" & FileName)
newWorkbook.Worksheets("A").Delete
newWorkbook.Close True
Reset
End Sub
Additionally, a couple of coding tips:
There's no need for Call - that function is deprecated and only exists to keep ancient code from blowing up
There is an extra concatenation of the "\" in your .SaveCopyAs line - simply put the trailing slash in with the rest of the path (as I did).
The unqualified Range("H2") refers to the ActiveWorksheet and could blow up on you if your user ever happens to click on a different worksheet while your code is running

VBA run time '1004' error when connected via VPN

I've searched through several forums and have found similar questions, but not my specific problem.
I have a macro that saves the active workbook to the specific user's folder, and saves a dated, xlsx, version in a sub folder. My macro-enable workbook is used by both in-office and remote associates. The in-office associates have no issue using this macro to save & archive the workbook to their folder, and, up until last week, the remote associates using VPN had no issues either.
However, over the past few days the remote associates using VPN have been receiving an error like run time error '1004': The specified dimensions are not valid for the current chart type and the code hangs on the ActiveWorkbook.SaveAs line at the end. Why would this error be coming up for a .SaveAs issue? I'm at a loss.
MainPath = "O:\Revenue Management\Centralized Revenue Management Service\CRMS Hotels\"
sPathSeek = MainPath & strPropNo & "*"
sFile = Dir(sPathSeek, vbDirectory)
sFileCheck = MainPath & sFile & "\Strategy Pack"
sBuildHist = MainPath & sFile & "\Strategy Pack\" & year1 & "\"
filePath = MainPath & sFile & "\Strategy Pack\" & propNo & " Strategy Pack.xlsm"
histPath = MainPath & sFile & "\Strategy Pack\" & year1 & "\" & propNo & " Strategy Pack " & STRdate & ".xlsx"
iLength = Len(Dir(sFileCheck, vbDirectory))
iLength2 = Len(Dir(sBuildHist, vbDirectory))
If iLength = 0 Then
MkDir (sFileCheck)
End If
If iLength2 = 0 Then
MkDir (sBuildHist)
End If
'Save Master Workbook
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=filePath,
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
The file I am trying to save over is also a .xlsm file.
I've tried removing all charts.
I've tried re-saving the master file.
It's worth noting that the same day this started happening, my VPN access would not log in until our systems administrator unlocked it (which was a first)

run-time error 1004 on backup macro that worked before and works on other users

I have a backup macro that runs every time when I save my excel file and saves a copy of the workbook into a folder.
Now I got a new computer where I use the same file, and it does not work anymore, I get run-time error 1004.
My co worker uses the same excel file and the same computer with another user and for him the macro works perfectly as it used to work for me on the other computer.
Code:
'backup
ora = ".h" & Hour(Now)
bufolder = ThisWorkbook.Path & "\excel_backups"
If Len(Dir(bufolder, vbDirectory)) = 0 Then
MkDir bufolder
End If
excfile = ThisWorkbook.Path & "\excel_backups\backup_" & Format(Date, "yyyy/mm/dd") & ora & "_" & ActiveWorkbook.name
If Dir(excfile) = "" Then
ActiveWorkbook.SaveCopyAs Filename:=bufolder & "\backup_" & Format(Date, "yyyy/mm/dd") & ora & "_" & ActiveWorkbook.name
End If
Edit: I get the error on line:
ActiveWorkbook.SaveCopyAs Filename:=bufolder & "\backup_" & Format(Date, "yyyy/mm/dd") & ora & "_" & ActiveWorkbook.name
It says:
Microsoft Office Excel cannot access the file '...'
There are several
possible reasons:
The file name of path does not exit. The file is being used by another
program. The Workbook you are trying to save has the same name as a
I don't think any of these problems may cause the problem.
Thank you for your time
The file cannot be saved because you are attempting to save the file name with your date formatted as "yyyy/mm/dd"? My computer will not allow me to save a file name with backslashes in it. Try changing the Format function to Format(Date, "yyyy-mm-dd").

Export As A Fixed Format Excel 2007

I have been assigned the task of developing a excel document that whole office will use. The user will click a button and the macro will export the file as a PDF to a shared folder. I wrote this code and tested this code using excel 2010. People that have excel 2007 where getting an error message saying "Run Time Error 1004 Document not saved. This document may be open, or an error may have been encountered when saving." I looked into the problem a little bit and found that excel 2007 needed an add-in update, so I installed it on their computers. I also checked to see if they have adobe on their computers and they do. They are still having the problem and I am unsure of what to do. Any help would be greatly appreciated!
Here is my code
' Define all variables
Dim strFileName As String
Dim folder As String
Dim member As Integer
Dim member_count As Integer
Dim member_name As String
Dim show As Variant
Dim MyTime As String
'Save as new file
Worksheets("Input data").Visible = True
folder = Sheets("Input data").Range("location").Value
MyTime = Time
Sheets("Input data").Select
Range("G2").Value = MyTime
strFileName = folder & "Material Request - " & Sheets("Input data").Range("name").Value & "_" & Sheets("Input data").Range("date").Value & " " & Sheets("Input data").Range("time").Value & ".pdf"
Sheets("Material Request").Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`
You should start with changing the code to remove .Select & .ActiveSheet instances.
Dim oWS as Worksheet
Set oWS = ThisWorkbook.Worksheets("Input data")
' Worksheets("Input data").Visible = True
folder = oWS.Range("location").Value
If Right(folder,1) <> Application.PathSeparator Then folder = folder & Application.PathSeparator
MyTime = Time
' Sheets("Input data").Select
oWS.Range("G2").Value = MyTime
strFileName = folder & "Material Request - " & oWS.Range("name").Value & "_" & oWS.Range("date").Value & " " & oWS.Range("time").Value & ".pdf"
Debug.Print "strFileName: " & strFileName
'Sheets("Material Request").Select
oWS.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`
Set oWS = Nothing
Refer to this MSDN Worksheet.ExportAsFixedFormat Method, you may need fill in more parameters depending on properties of the Worksheet "Input Data".
I have added some checks and refer to Immediate window to check value of strFileName in 2007.
I had a similiar problem (Error 1004 when attempting export). After an hour of pulling my hair out, here was the source of my problem.
I was passing a cell value as part of generating the filename. I was doing this in the format of
fileName:= ActiveWorkbook.Path & "\" & CStr(Workbooks.Cells(i,j).Value) & ".pdf"
The text in the cell itself was formatted to be in two rows (i.e. "top row text" + (Alt+K) + "bottom row text"). While the string looks normal in Debug.print, MsgBox, or value previews, I am thinking that there is a hidden character which encodes the new line for the cell. I believe this hidden character causes the error when passed as part of the fileName argument. I'm guessing Excel doesn't pick it up but the OS's file name system does.
In any case, this fixed the issue for me.