首页 > 解决方案 > 从其他工作表的单元格中获取值

问题描述

我制作了一个小的 VBA 代码,它从我的工作簿中获取了一个包含所有工作表名称的列表,我的问题是:
如何从 Sheet7 ("B4:B5")、Sheet8 ("B4:B5")、Sheet ( "B4:B5") ..... 进入 Sheet6,其中存在以下代码:

Private Sub Worksheet_Activate()
 Call task
End Sub
Sub task()
Call ThisWorkbook.speedOn
    Dim pws As Worksheet
    Dim x, N As Integer
    Dim browLastCol As Range
    Set pws = Sheets("Sheet6")
    'Set browLastCol = pws.Range(Cells(3, 4), Cells(3, 4).End(xlToRight))
    Set browLastCol = pws.Range(Cells(9, 2), Cells(9, 2).End(xlDown))
    
        x = 9
        
        pws.Range(Cells(3, 2), Cells(3, 2).End(xlToRight)).Clear

 
   For Each ws In Worksheets
    If ws.Name <> "Sheet1" Then
     If ws.Name <> "Sheet2" Then
       If ws.Name <> "Sheet3" Then
            If ws.Name <> "Sheet4" Then
             If ws.Name <> "Sheet5" Then
               If ws.Name <> "Sheet6" Then
               
                    Sheets("Sheet6").Cells(x, 2) = ws.Name ' List woksheets name 
                    
                     x = x + 1
                      Sheets("Sheet6").Range("A3").RowHeight = 40
                      
                      
                      With browLastCol
                               .RowHeight = 26
                               'Some code removed
                     End With
                      
                     
                 End If
                End If
             End If
         End If
      End If
   End If
Next ws
 Call ThisWorkbook.speedOff
End Sub

标签: excelvba

解决方案


其他人已经分享了一个重复的解决方案,但我会考虑使用Select Case这里来摆脱所有这些IF陈述。

For Each ws in Worksheets
    Select Case ws.Name
        Case "Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6"
            'Do Nothing (leave this blank)
        Else
            Sheets("Sheet6").Cells(x, 2) = ws.Name 
            x = x + 1
            Sheets("Sheet6").Range("A3").RowHeight = 40

            With browLastCol
                .RowHeight = 26
                'Some code removed
            End With

    End Select
Next ws

推荐阅读