简体   繁体   English

循环浏览excel中的每个选项卡,并通过VBA在Excel中逐个激活它

[英]Loop through each tabs in excel and active it one by one in Excel by VBA

I am trying to come up with a solution in VBA, what I want to do is to active each tab in this file and active certain cell for each tab based on different requirement. 我试图在VBA中提出一个解决方案,我想要做的是激活此文件中的每个选项卡,并根据不同的要求为每个选项卡激活某些单元格。 However my code didn't work, for the statement: 但是我的代码不起作用,对于该语句:

wkbk1.ws.Activate

It said Object doesn't not support this property or method(not sure why, my ws is the worksheet right?) 它说对象不支持此属性或方法(不知道为什么,我的工作表对吗?)

My code is: 我的代码是:

For Each ws In wkbk1.Worksheets
wkbk1.ws.Activate ' error here
If wkbk1.ws.Name = "Page" Then
wkbk1.ws.Range("B2").Select
ElseIf wkbk1.ws.Name = "Contents" Or "Results" Then
wkbk1.ws.Range("B1").Select
ElseIf wkbk1.ws.Name = "Logic" Then
wkbk1.ws.Range("C1").Select
Else
wkbk1.ws.Range("A1").Select
End If
Next

Can anyone please give me an idea for why I am having this issue? 谁能给我一个为什么我遇到这个问题的想法?

Don't use Activate (You don't need it) 不要使用激活(您不需要它)

Instead of using such a line 而不是使用这样的线

wkbk1.ws.Range("B2").Select

use Application.GoTo like this 像这样使用Application.GoTo

Application.Goto ws.Range("B2")

Just do a Select Case to determine the address to jump to for every sheet. 只需执行“ Select Case即可确定每张纸的跳转地址。 And finally use the Application.Goto method to jump there. 最后使用Application.Goto方法跳转到那里。

Option Explicit

Public Sub InitializeWorksheetsSelectedCells()
    Dim JumpToAddress As String

    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        Select Case ws.Name
            Case "Page"
                JumpToAddress = "B2"
            Case "Contents", "Results"
                JumpToAddress = "B1"
            Case "Logic"
                JumpToAddress = "C1"
            Case Else
                JumpToAddress = "A1"
        End Select

        Application.Goto ws.Range(JumpToAddress)
    Next ws
End Sub

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

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