简体   繁体   中英

Excel VBA for opening a file with a date in the filename that changes

I have an Excel file that is created every day, named "three day outlook 7-7-2014 . The date changes every day, but the files are stored by day in a folder, so I have multiple files named "three day outlook" but with different dates.

I am trying to use VBA code to open certain files by date that are selected by a date selection on another Excel sheet. I have tried the following:

Workbooks.Open Filename:=("C:\Users\sdfe\Documents\three day outlook" & Cells(D3).xlsx)

Try the following:

Workbooks.Open Filename:="C:\Users\sdfe\Documents\three day outlook " & Range("D3") & ".xlsx"

According to your question, there's a space character between the word "outlook" and the date. I assume the date is formatted on the sheet with the correct format. In fact, it might be better to show a message box with the path to the file you're trying to open. Something like:

MsgBox """C:\Users\sdfe\Documents\three day outlook " & Range("D3") & ".xlsx"""

and make sure this string is properly constructed before you use it.

Update (following your comment below):

Since your date is formatted as "7/7/2014" and not as "7-7-2014", there's a couple of things you can do:

  1. Format the cell where the date is (D3) as Text , so that it gets entered as you like and doesn't change by the date formatting.

  2. Format the cell where the date is (D3) with a Custom format of dm-yyyy and then above, instead of Range("D3") use Range("D3").Text .

  3. Keep the cell formatting as Date (as I assume it is), and then above, instead of Range("D3") use Format(Range("D3"), "dm-yyyy") .

Use the format function so that you always know what the date will appear like. Everyone will have a different date format set on their computer. And you never know if the computer just sends the date as just a number instead of a date.

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