首页 > 解决方案 > 打开 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

标签: excelvba

解决方案


如果我正确理解了这个问题,您只需要一个 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 

推荐阅读