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
Related
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
I have a few closed Excel workbooks, which I would be willing to access with =INDEX(MATCH) without openning them.
Unfortunately, I want to refer to them indirectly, thus based on the current sheet I am in.
E.g. - if I am in sheet -> then file path:
AAB -> 'C:\Users\vityata\Desktop\[AAB]Test'!$A:E
BBC -> 'C:\Users\vityata\Desktop\[BBC]Test'!$A:E
It seems like a trivial task, but the only options to do something like this seem to be the following:
Open the sheet and then use Indirect() (but I do not want to open the sheet)
Use VBA code (but it should be somehow reusable and really last resort)
Use data connection (I do not want it)
Use INDIRECT.EXT (but I do not want 3. party add-ins)
I have checked similar problems here: How to referencing value in closed excel workbook by formula incl. variable sheetname? but the first solution is rather too colmplicated to do it.
Any new ideas or best practices?
Update
So far I have achieved the following with VBA (although I would love to have a non-VBA solution):
Option Explicit
Public Sub VlookupClosedWb(Optional strLookFor As String = "Erteilung Baugenehmigung", _
Optional strSheet As String = "APF", _
Optional lngColIndex As Long = 2)
Dim strRange As String
strRange = "'" & ThisWorkbook.Path & "\[" & strSheet & ".xlsx]" & "Monatsbericht'!$A:$E"
ActiveCell.Formula = "=VLOOKUP(""" & strLookFor & """," & strRange & "," & lngColIndex & ",0)"
End Sub
Public Function fVlookupClosedWb(Optional strLookFor As String = "Erteilung Baugenehmigung", _
Optional strSheet As String = "APF", _
Optional lngColIndex As Long = 2)
Dim strRange As String
strRange = "'" & ThisWorkbook.Path & "\[" & strSheet & ".xlsx]" & "Monatsbericht'!$A:$E"
fVlookupClosedWb = WorksheetFunction.VLookup(""" & strLookFor & """, " & strRange & ", " & lngColIndex & ", 0)
End Function
Long story short - the Sub works as expected, providing exactly what I want in the active cell. The Function does not work. Any ideas how to make it work? I suppose that it does not work, because I am abusing a bit WorksheetFunction.VLookup, but I cannot pass a range without openning the other workbook. Ideas?
After some tries, I found out that the way to use some formulas on a closed excel workbook, without referring to the path is by using the Sumproduct() function.
E.g.:
If you want to use Sumproduct() as an alternative of Sumifs() this is how it looks like with two conditions:
=SUMPRODUCT(((B2:B6=C2)*1)*(A2:A6=D2))
*SUMPRODUCT(((B8:B13=C8)*1)*(A8:A13=D8))
*SUMPRODUCT(((B16:B20=C16)*1)*(A16:A20=D16))
I have put some more examples of it here.
I am trying to save a copy of an excel file through use of a marco but amend text after the current file name when saving. I have a macro that works, but it adds the file extension to the file name before I can amend text to it.
EG- my file is named "MyCurrentFile.xlsm", when I save it it adds the date, but keeps names the file "MyCurrentFile.xlsm01-14-16.xlsm".
Can I somehow remove the first .xlsm?
Code:
Sub Save_With_Todays_Date()
'
' Save_With_Todays_Date Macro
' Save a copy of the workbook with todays date at the end.
ThisWorkbook.SaveCopyAs _
Filename:=ThisWorkbook.Path & "\" & _
ThisWorkbook.Name & _
Format(Date, "mm-dd-yy") & ".xlsm"
End Sub
You can use the Workbook.FullName property and parse off the extension.
Dim fpfn as String
fpfn = ThisWorkbook.FullName
ThisWorkbook.SaveCopyAs _
Filename:=Left(fpfn, InStrRev(fpfn, Chr(46)) - 1) & Format(Date, "mm-dd-yy"), _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
I would recommend leaving the extension off the Workbook.SaveAs method and let the XlFileFormat Enumeration assign the correct extension. Hardcoding the extension reduces functionality and can result in an incorrect extension being applied to a SaveAs.
ThisWorkbook.Name = Replace(ThisWorkbook.Name, ".xlsm", Format(Date, "mm-dd-yy") & ".xlsm")
I made a macro to save an Excel file on a location based on some cell values.
But when I run the macro the file won't save.
The last line of the macro becomes yellow.
If I skip the dtMonth and dtMonthnumber the files saves just fine, so the problem is not dtYear, or Format(dtDate, "yymmdd").
Do I need to concert the cell values?
The formulas in the cells are to convert date to month and year:
U1 =TEXT(Controle!H6;"mmmm")
U2 =TEXT(Controle!H6;"jjjj")
U3 =TEXT(H6;"mm")
Dim dtDate As Date
dtDate = Date
Dim dtMonth As String
Dim dtYear As String
Dim dtMonthnumber As String
dtMonth = ThisWorkbook.Sheets("Controle").Range("U1")
dtYear = ThisWorkbook.Sheets("Controle").Range("U2")
dtMonthnumber = ThisWorkbook.Sheets("Controle").Range("U3")
Dim strFile As String
strFile = "M:\X-tra pakketten\" & dtYear & "\" & dtMonthnumber & " - " & dtMonth & "\" & Format(dtDate, "yymmdd") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=strFile, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Sounds like a VBA bug, where Breakpoints are sometimes not properly deleted. Try this:
Set a Breakpoint somewhere inside your procedure.
Change something inside your code, so it needs to recompile (for example add a Debug.Print "" somewhere)
Use the menu Debug > Delete all breakpoints (Ctrl+Shift+F9)
Recompile it
That should solve the problem. If it still doesn't work, copy your code somewhere, delete the module, create a new module and insert the code again.
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.