Open the file from previous month of User's input date in dialog box

lillypop

New Member
Joined
Jul 20, 2018
Messages
14
Hello,

I am trying to create a vba that will allow a user to enter his chosen date in the dialog box (eg. 20160730), then open a file from the previous month of his chosen date, as there is only 1 file per month in the folder (eg. 20160630_country.xlsm), and rename this file using the user's chosen date YYYYMMDD entered in the dialog box (20160730_country_xlsm). I've managed to get most done, except the part that should identify the file from the previous month. Any idea?



Dim fname As String
Dim fpath As String


fname1 = InputBox("enter date YYYYMMDD")
fname = fname1 & "_country.xlsm"
fpath = "C:\Users\Desktop"

Workbooks.Open Filename:= _
C:\Users\kc\Desktop\folder" & fname1 - 1 & "_data.xlsx" <---error here

ActiveWorkbook.SaveAs Filename:=fpath & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
Thanks. Will this code also work in January?

Hi,
It should do, updated code uses Cint function to coerce inpubox string year, month and day parts to numbers. These are then passed to DateSerial Function which returns a Date. .
DateAdd Function is then used to subtract 1 month from that date. If in you enter 20180131 code should return 20171231.

However, this only works if you save your files in a consistent way. For instance, in your if user enters 20180731 but previous file was saved 20180622 code won't find the file which is the concern JoeMo I think had.

If this does proved to be an issue, it can be overcome by modifying code to open files on Year Month values only.


Dave
 
Upvote 0

Forum statistics

Threads
1,224,827
Messages
6,181,194
Members
453,021
Latest member
pingpong7117

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top