excel - 打开 Excel 文件时如何运行两个代码之一?
问题描述
我想在打开 Excel 文件时运行代码。
如果从特定路径打开文件,则应运行单独的代码。
下面是 xlam 文件的“thisworkbook”部分中的代码。
Private Sub Workbook_Open()
MsgBox "You just ran this code"
Application.Run "SaveFile.Savefile"
End Sub
下面是从特定文件夹打开文件时要运行的代码。
Sub SaveFile()
MsgBox ActiveWorkbook.Name
Dim filepath As String
filepath = Application.ActiveWorkbook.path
If filepath = "D:\OneDrive - R.N. Kothari & Associates\Email Attachments" Then
MsgBox "we won"
Else
End If
End Sub
解决方案
如果我正确理解了这个问题,您只需要一个 if 语句来检查文件的当前位置。轻松完成,因为 excel 保存了每个打开的工作簿的路径,可通过Workbooks("Name").Path
或访问ThisWorkbook.Path
。所以你只需要把它放在 Workbook 模块中:
Private Sub Workbook_Open()
If ThisWorkbook.Path = Path1 Then
'Do Stuff
ElseIf ThisWorkbook.Path = Path2 Then
'Do Stuff
Else
'Do Stuff
End If
End Sub
推荐阅读
- powershell - 如何使用 powershell 传递参数?
- python - Python 类 - 存储和引用实例
- python - 如何在两个不同的 Github 存储库中同步一些文件夹?
- oop - 实现相同接口的不同类进入构造函数
- python - 具有重叠部分的图像的字符分割
- python - 如何从两个分组的列中找到数据集中的最大值
- pycharm - Pycharm调试器面板的个性化
- c++ - 为什么 noreturn/__builtin_unreachable 会阻止尾调用优化
- c# - 未注册“ProjectModels.Graphs.ProjectGraph”类型的服务
- r - R - 在地图中绘制不同颜色区域的轮廓