【问题标题】:Activate different workbook to run macro激活不同的工作簿以运行宏
【发布时间】:2015-03-15 10:24:15
【问题描述】:

我使用另一个工作簿中的活动工作表在我的工作簿中创建了一个宏。我现在想运行我的宏,但使用另一个不同的活动工作簿来获取我的数据。

我的宏中有 20 次这一行...

Windows("IFS_round_1").激活

...所以我不想在每次打开新工作簿运行宏时都更改它(例如 IFS_round_2)。有什么我可以添加的,所以宏只使用我打开的任何活动工作簿?

谢谢!

【问题讨论】:

    标签: excel


    【解决方案1】:

    创建一个变量来引用工作簿。例如:

    Sub Macro1()
        Dim wb as Workbook
        Set wb = ActiveWorkbook
    
        wb.Activate
    
        'DO CODE HERE
    End Sub
    

    这有帮助吗?

    【讨论】:

      【解决方案2】:

      我不知道您是否以编程方式打开另一个工作簿,但此解决方案有效。基本上你只要打开它就将句柄保存到另一个工作簿。

      sother_filename = "IFS_round_1"
      'saves the name of the current workbook
      curr_workbook = ActiveWorkbook.Name
      'opens the new workbook, this automatically returns the handle to the other
      'workbook (if it opened it successfully)
      other_workbook = OpenWorkbook(sother_filename)
      

      但这有什么好玩的呢? 只有两个工作簿打开时自动获取工作簿名称的另一种解决方案,然后只需使用它来调用另一个工作簿

      Function GetOtherWBName()
          GetOtherWBName = ""
      
          'if we dont have exactly two books open
          'we don't know what to do, so just quit
          If (Workbooks.Count) <> 2 Then
              Exit Function
          End If
      
          curr_wb = ActiveWorkbook.Name
      
          'if the active workbook has the same name as workbook 1
          If (StrComp(curr_wb, Workbooks(1).Name) = 0) Then
              'then the other workbook is workbook 2
              GetOtherWBName = Workbooks(2).Name
          Else
              'then this is the other workbook
              GetOtherWBName = Workbooks(1).Name
          End If
      
      End Function
      

      所以现在在具有宏的工作簿中创建一个按钮并为其分配一个类似于此的宏

      Sub ButtonClick()
          'first we save the current book, so we can call it easily later
          curr_wb = ActiveWorkbook.Name
      
          other_wb = GetOtherWBName()
      
          If Len(other_wb) = 0 Then
              MsgBox ("unable to get other wb")
              Exit Sub
          End If
      
          'now to call the other workbook just use
          Workbooks(other_wb).Activate
      
          'all the rest of your code
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-28
        • 2014-07-02
        • 1970-01-01
        • 2017-01-16
        • 2019-03-03
        • 1970-01-01
        相关资源
        最近更新 更多