关闭 excel 中每周更改名称的工作簿
Close workbook in excel with name changing weekly
我有一个包含以下宏的文件。基本上我需要它来关闭所有打开的工作簿,但是我的一个文件名每周都会更改,例如,本周它被称为特殊服务 1503,下周它将是特殊服务 1504 等。关于如何编辑的任何想法下面的代码,以便我可以关闭此文件而无需手动编辑 vba 中的数字?
Workbooks("2014 Actuals").Close SaveChanges = True
Workbooks("Special Services Budget 2015").Close SaveChanges = True
上面的工作因为没有编辑,下面的工作但我必须每周手动将周数从 1504 更改为 1505 等。
Workbooks("Special Services 1504").Close SaveChanges = True
有什么想法吗?
如果我理解了逻辑,你只需要建立一个动态索引:
firstWeek2015 = 1500 '<-- starting seed
yearFactor = Year(Now()) - 2015 '<-- we take the current year and we subtract 2015: this year it will be 0, next year 1 etc.
weekFactor = WorksheetFunction.WeekNum(Now()) '<--we just take the current week
newIndex = firstWeek2015 + yearFactor*52 + weekFactor
并将其替换为您的工作簿名称:
Workbooks("Special Services " & newIndex).Close SaveChanges = True
即使我宁愿:
1) Use the same logic that you used to open the file;
2) Use a RegEx-based solution (if "Special Services ????" is the only file of that kind).
我将其添加为一个单独的答案,因为它与之前的方法完全不同:
当且仅当您确定只有该工作簿的名称类似于 Special Services 1054,那么您可以像这样使用 Like 运算符 :
For Each objWb In Workbooks
If objWb.Name Like "Special Services *"
objWb.Close SaveChanges = True
End If
Next objWb
如我之前的回答所述,这种方法比另一种方法更可靠但前提是您 100% 确定可能不会打开另一个具有相似名称的工作簿.
我有一个包含以下宏的文件。基本上我需要它来关闭所有打开的工作簿,但是我的一个文件名每周都会更改,例如,本周它被称为特殊服务 1503,下周它将是特殊服务 1504 等。关于如何编辑的任何想法下面的代码,以便我可以关闭此文件而无需手动编辑 vba 中的数字?
Workbooks("2014 Actuals").Close SaveChanges = True
Workbooks("Special Services Budget 2015").Close SaveChanges = True
上面的工作因为没有编辑,下面的工作但我必须每周手动将周数从 1504 更改为 1505 等。
Workbooks("Special Services 1504").Close SaveChanges = True
有什么想法吗?
如果我理解了逻辑,你只需要建立一个动态索引:
firstWeek2015 = 1500 '<-- starting seed
yearFactor = Year(Now()) - 2015 '<-- we take the current year and we subtract 2015: this year it will be 0, next year 1 etc.
weekFactor = WorksheetFunction.WeekNum(Now()) '<--we just take the current week
newIndex = firstWeek2015 + yearFactor*52 + weekFactor
并将其替换为您的工作簿名称:
Workbooks("Special Services " & newIndex).Close SaveChanges = True
即使我宁愿:
1) Use the same logic that you used to open the file;
2) Use a RegEx-based solution (if "Special Services ????" is the only file of that kind).
我将其添加为一个单独的答案,因为它与之前的方法完全不同:
当且仅当您确定只有该工作簿的名称类似于 Special Services 1054,那么您可以像这样使用 Like 运算符 :
For Each objWb In Workbooks
If objWb.Name Like "Special Services *"
objWb.Close SaveChanges = True
End If
Next objWb
如我之前的回答所述,这种方法比另一种方法更可靠但前提是您 100% 确定可能不会打开另一个具有相似名称的工作簿.