Excel VBA 用于打开文件名中日期发生变化的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25223585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA for opening a file with a date in the filename that changes
提问by user3146807
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.
我有一个每天创建的 Excel 文件,名为"three day outlook 7-7-2014
. 日期每天都在变化,但文件按天存储在一个文件夹中,所以我有多个命名"three day outlook"
但日期不同的文件。
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:
我正在尝试使用 VBA 代码按日期打开某些文件,这些文件由另一个 Excel 工作表上的日期选择选择。我尝试了以下方法:
Workbooks.Open Filename:=("C:\Users\sdfe\Documents\three day outlook" & Cells(D3).xlsx)
回答by djikay
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:
由于您的日期格式为“7/7/2014”而不是“7-7-2014”,因此您可以执行以下操作:
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.
Format the cell where the date is (D3) with a Customformat of
d-m-yyyy
and then above, instead ofRange("D3")
useRange("D3").Text
.Keep the cell formatting as Date(as I assume it is), and then above, instead of
Range("D3")
useFormat(Range("D3"), "d-m-yyyy")
.
将日期为 (D3) 的单元格格式化为Text,以便根据需要输入它并且不会因日期格式而改变。
将日期为 (D3) 的单元格格式化为,然后在上方使用自定义格式
d-m-yyyy
,而不是Range("D3")
使用Range("D3").Text
。将单元格格式保持为Date(我认为是),然后在上面,而不是
Range("D3")
使用Format(Range("D3"), "d-m-yyyy")
.
回答by user1644564
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.
使用格式功能,以便您始终知道日期的显示方式。每个人的计算机上都会设置不同的日期格式。而且您永远不知道计算机是否只是将日期作为数字而不是日期发送。