简体   繁体   中英

Excel Macro for saving under cell value

I am new to all this coding stuff and am trying to create a Macro that once used will save the active worksheet as the name of whatever the date is entered in cell "D2". I am using excel 2010. I found some code that will save the sheet to my specified folder but nothing yet that will save it as whatever is in cell "D2".

this is the code I'm using right now:

Sub Save_GPR()
   Application.ScreenUpdating = False
   ActiveSheet.Select
   ActiveSheet.Copy
   ThisFile = Range("Q1").Value
   ActiveWorkbook.SaveAs "C:\Users\owner\Desktop\FlightLog", FileFormat:=52
   Application.ScreenUpdating = True
   ActiveWorkbook.Close
End Sub

any help would really be appreciated. thanks!

The following edit should for you. I removed the Activesheet.Select/Copy as it was superflous.

Sub Save_GPR()
   Application.ScreenUpdating = False

   'grab the file name from D2, put it in variable ThisFile
   ThisFile = ActiveSheet.Range("D2").Value

   'Save the activeworkbook. Use the filename in ThisFile variable
   ActiveWorkbook.SaveAs "C:\Users\owner\Desktop\" & ThisFile, FileFormat:=52


   Application.ScreenUpdating = True
   ActiveWorkbook.Close
End Sub

Try changing your code into the following:

Sub Save_GPR()
   Application.ScreenUpdating = False

   'Exit if D2 is empty
   If Activesheet.Range("D2").Value = vbNullString Then Exit Sub

   ThisFile = Activesheet.Range("D2").Value

   ActiveWorkbook.SaveAs "C:\Users\owner\Desktop\" & ThisFile, FileFormat:=52
   Application.ScreenUpdating = True
   ActiveWorkbook.Close
End Sub

I have removed the code that did not have anything to do with the task you have described. I have added a line of code that will cancel the procedure if cell D2 is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM