我有一个关于如何做某事的想法的简单问题。 我的宏需要将当前打开的工作簿保存为新工作簿。通常它很简单,但如果文件名包含某个日期,则需要将其更改为今天的日期。
一些例子:
我的问题是我怎样才能尽可能简单?我应该编码一堆IF吗?最后如何更换它?在IF我可以使用LIKE运算符,但在替换中我需要在参数中提供原始字符串..
感谢您的时间和帮助!
答案 0 :(得分:0)
我在这里找到了这段代码:http://www.mrexcel.com/forum/excel-questions/632128-visual-basic-applications-extract-date-text.html
我已将其更新为单个日期并以字符串形式返回日期,但您需要更新模式以处理其他格式。希望其他人可以帮助你。
Sub CallIt()
Dim MyDate As String
If DateRet(Range("B2").Text, MyDate) Then
MsgBox MyDate
Else
'... something to handle if the string is glitched in some manner.
End If
End Sub
Function DateRet(ByVal CellText As String, sDate As String) As Boolean
Static REX As Object ' RegExp
Dim rexMC As Object ' MatchCollection
Dim dTemp As Date
Dim ValsSplit As Variant
If REX Is Nothing Then
Set REX = CreateObject("VBScript.RegExp")
With REX
.Global = True
.Pattern = "\b[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}\b"
End With
End If
With REX
If .Test(CellText) Then
Set rexMC = .Execute(CellText)
If rexMC.Count = 1 Then
sDate = .Execute(CellText)(0)
DateRet = True
Else
DateRet = False
End If
Else
DateRet = False
End If
End With
End Function
答案 1 :(得分:0)
编辑
你可以试试这个
Option Explicit
Sub main()
Dim wbName As String, wbExt As String
With ActiveWorkbook
wbName = Mid(.Name, 1, InStrRev(.Name, ".") - 1)
wbExt = Mid(.Name, InStrRev(.Name, "."))
If IsDate(Right(wbName, Len(wbName) - InStrRev(wbName, " "))) Then ' check for a possible "date" part ofthe name
wbName = Left(wbName, InStrRev(wbName, " ")) & "v" & Format(Date, "yyyy-mm-dd")
Else
wbName = "v" & Format(Date, "yyyy-mm-dd")
End If
.SaveAs wbName & wbExt
End With
End Sub
它依赖于" IsDate" VBA功能。希望用户没有太多关于如何键入约会的幻想......