如何隐藏和使用从用户窗体数据录入工作表取消隐藏

问题描述 投票:0回答:1

我不知道为什么我得到了范围下标错误的。当我点击combobox1并选择一个项目,MaternityForm组合框填充了我的工作簿中的工作表。然后我想在MaternityForm选择了一个分开隐藏其他工作表。然后,将活性片将接收来自用户窗体数据,但我得到标超出范围错误..

    Private Sub Get_Data_Click()
           Dim ws As Worksheet
           Dim xWs As Worksheet

           For Each xWs In Application.ActiveWorkbook.Worksheets
              xWs.Visible = True
           Next

           Set ws = Worksheets(MaternityForm.Value)
           Sheets(MaternityForm.Value).Activate
           On Error Resume Next

           For Each ws In Application.ActiveWorkbook.Worksheets
               if ws.Name <> MaternityForm.Value Then
                  ws.Visible = xlSheetHidden
               End If
           Next

           With Sheets(MaternityForm.Value)
             .Range("B3").Value = Me.NameBox.Text
             .Range("f3").Value = Me.PaynoBox.Text
             .Range("B6").Value = Me.DTPicker1.Value
             .Range("B7").Value = Me.DTPicker2.Value
             .Range("B17").Value = Me.FirstPayBox.Value
             .Range("B18").Value = Me.SecondPayBox.Value
             .Range("B25").Value = Me.MonthlyPayBox.Value
            .Range("H7").Value = Me.DTPicker3.Value
         End With

   End Sub   
excel
1个回答
0
投票

你混淆了你的变量wsxWs


ws指的是一个特定的表,而xWs是您的变量工作表。因此,你的第二个循环是无效的(这好像是说For Each Sheet1 in Worksheets)。

您可以通过您的变量工作表需要循环,并将它们与特定表

   For Each xWs In Application.ActiveWorkbook.Worksheets
       if xWs.Name <> ws.Name Then
          xWs.Visible = xlSheetHidden
       End If
   Next

有了这样说,没有必要循环两次。

需要注意的是ws.Name = MaterityForm.Value将返回TRUEFALSE。这样做的结果确定ws.Visible = TRUE/FALSE

Private Sub Get_Data_Click()

Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets
    ws.Visible = ws.Name = MaternityForm.Value
Next ws

With Sheets(MaternityForm.Value)
    .Range("B3").Value = Me.NameBox.Text
    .Range("f3").Value = Me.PaynoBox.Text
    .Range("B6").Value = Me.DTPicker1.Value
    .Range("B7").Value = Me.DTPicker2.Value
    .Range("B17").Value = Me.FirstPayBox.Value
    .Range("B18").Value = Me.SecondPayBox.Value
    .Range("B25").Value = Me.MonthlyPayBox.Value
    .Range("H7").Value = Me.DTPicker3.Value
End With

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.