【问题标题】:Avoiding the use of worksheet.activate in order to execute code避免使用 worksheet.activate 来执行代码
【发布时间】:2019-05-29 09:20:23
【问题描述】:

这应该很容易。我想减少代码worksheets("Sheet1").activate 的使用,因为它很麻烦而且经常出错,但是我尝试过的所有尝试都不起作用。到目前为止,我已经使用了 set worksheet 选项和 with worksheet 选项,但除非我严格在 Excel 上的工作表 1 上,否则代码不会执行。

我尝试了此链接中列出的一些选项,但没有一个有效:How to avoid using Select in Excel VBA。我真的开始认为我需要一直使用激活。

例如这样的代码:

Sub test()
Dim Cols As integer
Cols = Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count
End sub

我希望即使我不在 Sheet1 上也会执行此代码,因为我已经明确定义了必须在其中执行它的工作表。但是,除非我在该工作表上,否则代码不起作用。作为背景信息,我在 VBA 模块部分的子程序下运行我的大部分代码。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    你已经很接近正确了。

    您需要记住为 每个 范围对象引用 WB 和 WS。否则,VBA 将引用 active WB 和 WS

    Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count 中,我计算了两个需要引用的Cells 范围对象。
    此外,您的工作簿没有为您所指的工作表指定。如果活动工作簿中没有名为“Sheet1”的工作表,您将收到 Subscript out of Range 错误。

    为防止此类错误,最好使用With...End With 语句。这样,您只需先指定工作簿和 -sheet,防止代码混乱。

    所以,应该是:

    With Workbooks(REF).Sheets("Sheet1")
        .Range(.Cells(1, 1), .Cells(1, 1).End(xlToRight)).Count
    End With
    

    【讨论】:

      【解决方案2】:

      看看这是否有助于理解缺失的内容:

      Option Explicit
      Sub test()
      
          'Your code:
          Cols = Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count 'Cells inside the range are not qualified
      
          'Corrected code:
          Cols = Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(1, 1), Worksheets("Sheet1").Cells(1, 1).End(xlToRight)).Count
      
          'Above code is too long right?
      
          'Option 1        
          Dim ws As Worksheet
          Set ws = ThisWorkbook.Sheets("Sheet1")
          Cols = ws.Range(ws.Cells(1, 1), ws.Cells(1, 1).End(xlToRight)).Count
      
          'Option 2
          With ThisWorkbook.Sheets("Sheet1")
              .Range(.Cells(1, 1), .Cells(1, 1).End(xlToRight)).Count
          End With
      
          'Changing your code works with any option:
          With ThisWorkbook.Sheets("Sheet1")
              .Cells(1, .Columns.Count).End(xlToLeft).Column 'This option goes from right to left to find the last column with data
          End With
      
      End Sub
      

      此外,始终限定工作表和 工作簿 似乎使用工作表就足够了,但如果您使用超过 1 个不合格的工作簿,这也是一个问题。

      【讨论】:

        猜你喜欢
        • 2014-05-15
        • 1970-01-01
        • 1970-01-01
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-18
        相关资源
        最近更新 更多