workers,
I have this code at the moment;
Public Sub SaveAsA1()
ActiveWorkbook.SaveAs Filename:=Range("P4").Value & ";" & Range("F6").Value & ";" & Range("R6").Value & ";" & Range("R4").Value
End Sub
Which i would like to modify to be saved in a certain filemap; \S31000265\Users$\NR4236\My Documents\TV-01-project\TestmapWeek9GOED. Been trying but it keeps overwriting the Filename-code. Hope you guys can help me out.
Public Sub SaveAsA1()
ChDir ("C:\work\testout\") ' Directory you need to save the file as xlsm
Filename = Range("P4").Value & ";" & Range("F6").Value & ";" & Range("R6").Value & ";" & Range("R4").Value
ActiveWorkbook.SaveAs Filename:=Filename, FileFormat:=52
End Sub
Related
I have a macro that created a folder by data within a pathway, and I want a cut of a manager roster to be saved in that folder. Since the folder name varies, this needs to be dynamic.
I want it to go something like this:
Dim sPath As String
sPath = "M:\mgr1_TCR_Reports\"
If Len(Dir(sPath & "_" & Format(Date, "mm_dd_yyyy"), vbDirectory)) = 0 Then
MkDir (sPath & "_" & Format(Date, "mm_dd_yyyy"))
End If
End Sub
and saving this like:
.SaveAs Filename:="M:\mgr1_TCR_Reports\" & "_" & Format(Date, "mm_dd_yyyy_") & "\" & Manager, FileFormat:=xlOpenXMLWorkbook, Password:=""
.Close
But I keep getting a runtime 1004: document not saved on ^^^ the second line of code I provided.
Any idea what's going on?
I'm familiar with VBA but I am not a programmer so any help I can get in this matter is greatly appreciated. I have a report object that is mailed as a .pdf file. This portion of the code works fine but I would like to be able to save a copy of this file to a specific location with a unique name that includes the date and time the file was created. The first set of code is the SendObject that works the second set of code does not work, it is a separate procedure I have been testing to save the object. Once I can get it working I was going to integrate it into first. I would appreciate any help.
Private Sub Command21_Click()
DoCmd.SetWarnings (False)
Dim mailto As String
Dim ccto As String
Dim bccto As String
mailto = "Safety-RiskGroup#bargeacbl.com"
ccto = ""
bccto = ""
emailmsg = "The attached document is the updated Case Log." & vbNewLine
& "Please review the report, contact me and you find any discrepancies. "&vbNewLine & vbNewLine & "Thank You, " & vbNewLine & vbNewLine & vbNewLine & "Cary S. WInchester" & vbNewLine & "American Commercial Barge Line" & vbNewLine & "Safety Department"
mailsub = "Updated Case Log Report"
On Error Resume Next
DoCmd.SendObject acSendReport, "rpt_CaseLog-CurrentYear", acFormatPDF, mailto, ccto, bccto, mailsub, emailmsg, True
DoCmd.SetWarnings (True)
End Sub
This is the second set of code to attempt to save the object to a specific path with a unique name.
Private Sub Command23_Click()
On Error GoTo Command23_Click_Err
Dim filePath As String
filePath = "C:\Work\ACBL\Access Dbase\DayCount" & "CaseLog" _
& Format(Date, " yyyy/mm/dd") _
& Format(Time, " hh:MM:ss") & ".pdf"
DoCmd.OutputTo acOutputReport, "rpt_CaseLog-CurrentYear", _
"PDFFormat(*.pdf)", filePath, _
False, "", , acExportQualityPrint
Command23_Click_Exit:
Exit Sub
Command23_Click_Err:
MsgBox Error$
Resume Command23_Click_Exit
End Sub
Thanks Bit Accesser but that was not the problem, the code was laid out as it should be; however, the Date and Time formats were using characters that could be used for a file name, specifically, the colons and the backslashes were causing it to fail. Below is the corrected code. There are a few other spots I tweaked but this works great.
Private Sub Command25_Click()
On Error GoTo Command25_Click_Err
Dim filePath As String
filePath = "C:\Work\ACBL\Access Dbase\DayCount\Reports\"
DoCmd.OutputTo acOutputReport, "rpt_CaseLog-CurrentYear", acFormatPDF, _
filePath & " Case Log Update" & Format(Now(), " dd-mm-yyyy hhmmss") & ".pdf"
Command25_Click_Exit:
Exit Sub
Command25_Click_Err:
MsgBox Error$
Resume Command25_Click_Exit
End Sub
Background:
Several years ago, I made a spreadsheet to generate a list of samples to be tested each day. The user (usually me) checks boxes to indicate which tests' samples to list. Then the "save load sheet" button uses VBA to requery a database connection for sample information, populates the formatted list through a complex series of formulas, copies the values from the formula sheet ("Generator") to another sheet ("LoadSheet"), copies that sheet to a new workbook, and saves it with the date as filename in a folder according to year and month.
It worked pretty dependably for about 5 years, right up until a couple of weeks ago when my computer was upgraded from Windows 7 with Office 2013 to Windows 10 with Office 2016.
Problem:
Now, when I try to execute the code, I get Runtime error '1004: Copy method of Worksheet class failed."
Sub SaveAs()
'Copy to new workbook.
Sheets("LoadSheet").Copy '<---This is the line that fails.
' Check directory, create if necessary.
If Dir("G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\", vbDirectory) = "" Then
If Dir("G:\Load Sheets\" & Year(Now) & "\", vbDirectory) = "" Then
MkDir ("G:\Load Sheets\" & Year(Now) & "\")
End If
MkDir ("G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\")
End If
'Save.
'If the worksheet already exists, the user will be asked whether to replace the file or not.
'If it already exists and is currently open, an error could arise.
'Hopefully that won't come up before I have time to think of a way to implement error handling.
ActiveWorkbook.SaveAs Filename:= _
"G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\" & Format(Now, "mm-dd-yy") & "x", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Range("A1").Select
Sheets(1).Select
Range("A1").Select
ActiveWorkbook.Save
Application.CutCopyMode = False
ThisWorkbook.Activate
Workbooks(Format(Now, "mm-dd-yy") & "x.xlsx").Activate
End Sub
This is the code that saves the file. It fails on the line indicated.
What I've already tried:
I've tried right-clicking on the worksheet tab, clicking "Move or Copy..." and try to create a copy in a new workbook. Nothing happens. No error message, no new worksheet/book, nothing.
Same thing happens if I try to "move" rather than "copy."
If I try right-clicking and creating a copy in the same workbook, I get a new blank sheet, rather than a copy.
I tried repairing my Office installation, but that didn't help.
I read about some cases where users suspected file corruption, so I even tried manually copying the contents to a new workbook by Ctrl+A,C,V one sheet at a time, and then doing the same for the code. No effect.
I tried Sheets(Worksheets.Count).Select followed by ActiveSheet.Copy, since the sheet is the last one in the book, but of course that didn't work.
I read that it could be because the workbook needed to be saved first, so I tried ActiveWorkbook.Save before the copy. Still the same result.
I tried decompiling/recompiling the worksheet to no effect.
It worked fine on Windows 7 with Office 2013 (and still does on a co-worker's Win7/Excel2013 machine), but I couldn't find anything online about problems with the Sheets.Copy method in Excel 2016, so I don't know if either of those is relevant.
Any ideas?
EDIT: I've tried it on an identical computer (also running Windows 10 & Office 2016) and had the same result. I'm not sure how commonly an installation becomes corrupted, but this feels like more than coincidence. The other computer is rarely used by anyone, and it's being used primarily to run an instance of SQL Server Express and a Windows service I wrote, so I suspect that makes corruption even less likely.
I've got a workaround for now... I just save the file with the filename and path I would have used for the copy, then do a For Each on each worksheet, deleting anything not named "LoadSheet."
Sub SaveAs()
On Error GoTo SaveAs_Err
'Check directory, create if necessary.
If Dir("G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\", vbDirectory) = "" Then '<> "G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\" Then
If Dir("G:\Load Sheets\" & Year(Now) & "\", vbDirectory) = "" Then '<> "G:\Load Sheets\" & Year(Now) & "\" Then
MkDir ("G:\Load Sheets\" & Year(Now) & "\")
End If
MkDir ("G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\")
End If
' Turn off alerts. They're annoying. I don't care if it's poor form, I just want to be done with this. I'm not being paid to write code.
Application.DisplayAlerts = False
'Save, disregarding consequences.
ActiveWorkbook.SaveAs Filename:= _
"G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\" & Format(Now, "mm-dd-yy") & "x", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
' Remove extraneous sheets.
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
If ws.Name <> "LoadSheet" Then ws.Delete
Next
Application.DisplayAlerts = True
Exit Sub
SaveAs_Err:
Application.DisplayAlerts = True
MsgBox ("An error occurred while saving the file.")
Debug.Print "Error " & Err.Number & ": " & Err.Description
End Sub
I'm still interested in fixing the root cause of this problem, so if anyone has ideas, I'm all ears! I'll probably still try the uninstall/reinstall, but I don't expect it to change anything.
Brute force fix, try:
Sub SaveAs()
Dim newWB as Workbook, i as Integer, copyRange as Range, fName as String
Set newWB = Workbooks.Add
While newWB.Worksheets.Count > 1
newWB.Worksheets(newWB.Worksheets.Count).Delete
Wend
newWB.Worksheets(1).Name = "LoadSheet"
' get a handle on the sheet's usedRange object
Set copyRange = ThisWorkbook.Worksheets("LoadSheet").UsedRange
' assign the values to the newWB.Worksheets(1)
'newWB.Worksheets(1).Range(copyRange.Address).Value = copyRange.Value
copyRange.Copy Destination:=newWB.Worksheets(1).Range(copyRange.Address)
'Check directory, create if necessary.
If Dir("G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\", vbDirectory) = "" Then
If Dir("G:\Load Sheets\" & Year(Now) & "\", vbDirectory) = "" Then
MkDir ("G:\Load Sheets\" & Year(Now) & "\")
End If
MkDir ("G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\")
End If
fName = "G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\" & Format(Now, "mm-dd-yy") & "x"
If Dir(fName & ".xlsx") <> "" Then Kill fName & ".xlsx"
If Dir(fName & ".xlsm") <> "" Then Kill fName & ".xlsm"
newWB.SaveAs Filename:= fName, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Workbooks.Open(fName)
End Sub
Alternatively, use the SaveAs method of the Worksheets class:
Sub SaveAs()
Dim fName as String
'Check directory, create if necessary.
If Dir("G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\", vbDirectory) = "" Then
If Dir("G:\Load Sheets\" & Year(Now) & "\", vbDirectory) = "" Then
MkDir ("G:\Load Sheets\" & Year(Now) & "\")
End If
MkDir ("G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\")
End If
fName = "G:\Load Sheets\" & Year(Now) & "\" & MonthName(Month(Now)) & "\" & Format(Now, "mm-dd-yy") & "x"
If Dir(fName & ".xlsx") <> "" Then Kill fName & ".xlsx"
If Dir(fName & ".xlsm") <> "" Then Kill fName & ".xlsm"
ThisWorkbook.Worksheets("LoadSheet").SaveAs Filename:= fName, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWorkbook.Save
Application.CutCopyMode = False
Workbooks.Open(fName)
End Sub
I've also revised both solutions to avoid the potential error you comment:
If it already exists and is currently open, an error could arise.
I would work with your IT and/or MS support on the specific failure of the .Copy method, though, it's almost certainly a problem with your installation and may result in nastier errors in the future.
I'm relatively new to VBA and working on something for work that will launch a given folder in explorer, run a search in explorer for files in that folder whose names contain a certain string, and show me the results in explorer. I've been using shell, and was able to individually open a specific folder, and run a search...but I can't figure out how to do both tasks simultaneously.
Here's some different things I've tried: nothing has worked.
Sub search_Files()
Dim folderName As String
folderName = "\\Users\itsMe\Documents"
Call Shell("C:\WINDOWS\explorer.exe "" "" & folderName _
&"" ""&search-ms://query=h&", vbNormalFocus)
Call Shell("explorer.exe "" ""search-ms:query=h&crumb=location:\\Users\itsMe\Documents", vbNormalFocus)
Call Shell("C:\WINDOWS\explorer.exe"" & FolderName &", vbNormalFocus)
RetVal = Shell( _
"c:\Windows\explorer.exe ""search-ms:displayname=Search%20Results&crumb=\\Users\itsMe\Documents" _
& h & "%20kind%3A%3Dfolder&crumb=location:" _
& folderName, vbNormalFocus)
End Sub
Could someone please provide me with the proper code on how to do this? (I want to use shell.)
Try this - it worked for me...
Call Shell("explorer.exe " & Chr(34) & "search-ms:query=*.pdf&crumb=location:c:\ad\" & Chr(34), vbNormalFocus)
Do you mean your code need to replace the fifth one as below? I am tried to modify the related destination folder already. But still fail. Not sure I did wrong in which step.
Sub search_Files()
Dim folderName As String
folderName = "C:\Users\lkam\Documents"
Call Shell("C:\WINDOWS\explorer.exe "" "" & folderName _
&"" ""&search-ms://query=h&", vbNormalFocus)
Call Shell("explorer.exe " & Chr(34) & "search-ms:query=*.pdf&crumb=location:c:\ad\" & Chr(34), vbNormalFocus)
Call Shell("C:\WINDOWS\explorer.exe"" & FolderName &", vbNormalFocus)
RetVal = Shell( _
"c:\Windows\explorer.exe ""search-ms:displayname=Search%20Results&crumb=C:\Users\lkam\Documents" _
& h & "%20kind%3A%3Dfolder&crumb=location:" _
& folderName, vbNormalFocus)
End Sub
I am working on a backup script in VBS that creates a folder and then copies a powerpoint file into the most recently created folder.
Everything works great except MoveFile command at the bottom
Here is what I got so far (the bottom code is most important but just so everyone can understand where I am coming from):
sourceDir = "T:\Team"
destinationDir = "T:\Team\Archive\Archive"
const OverwriteExisting = True
intNum = 1
strDirectory = destinationDir & "_" & replace(date,"/",".") & "_" & intNum
'This checks if the folder exists and if not it will create a folder with the date and increment the folder name incase there are multiple updates in a single day.
if not filesys.FolderExists(destinationDir) then
While filesys.FolderExists(destinationDir & "_" & replace(date,"/",".") & "_" & intNum) = True
intNum = intNum + 1
Wend
Set archivefolder = filesys.CreateFolder(destinationDir & "_" & replace(date,"/",".") & "_" & intNum)
Else
Set archivefolder = filesys.CreateFolder(destinationDir)
Set objFolder = fso.CreateFolder(strDirectory)
End if
Dim thisday, thisdayy, thisdayyy
Today_Date()
' This is the problem code
filesys.MoveFile "T:\Arriva\Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm", "destinationDir & "\" & Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm"
Function Today_Date()
thisday=Right(Day(Date),2)
thisdayy=Right("0" & Month(Date),2)
thisdayyy=Right("0" & Year(Date),2)
End Function
This results in a folder being created as "T:\Team\Archive\Archive_03.12.2014_1
My goal is to be able to move the file in T:\Team to the dynamically created folder above.
Everything works great until the MoveFile part. The destination is the part throwing a "type mismatch" at the line where I define the strDirectory
I am just learning this type of programming so please let me know if I can provide any further details!
Thank you in advance!
You have a couple syntax errors with your quotes that are cancelling each other out. Change your line to this:
filesys.MoveFile "T:\Team\Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm", "destinationDir" & "_" & replace(date,"/",".") & "_" & intNum & "\" & "Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm"