简体   繁体   English

VBA 错误:Worksheet 类的激活方法失败

[英]VBA error: Activate method of Worksheet class failed

Hi guys I have this bunch of code:嗨,伙计们,我有一堆代码:

  For Each ws In ThisWorkbook.Sheets
    If ws.Name = "Position calculation" Or ws.Name = "Strategies & weights" Then
    Else
        sheet_name = ws.Name
        Sheets(sheet_name).Visible = True
        ThisWorkbook.Worksheets(sheet_name).Activate
        ws.Range("A2").Select
        For Each c In Range("A2", "A1000")
            If c.Value = "" Then
                c.Activate
                searched_cell = ActiveCell.Offset(-1, 0).Address
                GoTo flag1
            End If
        Next c

Everytime when I try to run a code from a sheet called "Position calculation" I get the error saying每次当我尝试从名为“位置计算”的工作表运行代码时,我都会收到错误消息

Run - time error '1004' Activate method of Worksheet class failed运行时错误 '1004' Worksheet 类的 Activate 方法失败

I cannot distinguish why the code is running from other sheets, but I have to run this script exactly from the page causing me this sort of error.我无法区分为什么代码是从其他工作表运行的,但是我必须完全从导致此类错误的页面运行此脚本。

Thank you in advance for your help预先感谢您的帮助

I couldn't figure out why you receive the error that you complain about but it's certainly true that you wouldn't have the problem if you wouldn't ask for it (as has been pointed out to you by @Siddarth Rout in the comments above).我无法弄清楚为什么您会收到您抱怨的错误,但如果您不要求它,您肯定不会遇到问题(正如@Siddarth Rout 在评论中向您指出的那样)以上)。 In my analysis I found that your entire approach is a little cranked even if all Select and Activate statements are removed.在我的分析中,我发现即使删除了所有SelectActivate语句,您的整个方法还是有点曲折。 Please consider the approach taken below.请考虑下面采取的方法。

Private Sub Try()

    Dim Ws      As Worksheet
    Dim NextRow As Long
    
    For Each Ws In ThisWorkbook.Worksheets
        With Ws
            If .Name <> "Position calculation" And .Name <> "Strategies & weights" Then
                NextRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
                If NextRow <= 1000 Then Exit For
            End If
        End With
    Next Ws
    
    NextRow = WorksheetFunction.Max(NextRow, 2)
    MsgBox Ws.Name & vbCr & "cell " & Cells(NextRow, "A").Address(0, 0)
End Sub

This code will return the same result whichever sheet is active and regardless of whether a sheet is hidden or visible.无论工作表处于活动状态还是隐藏或可见,此代码都将返回相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM