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

时间:2019-02-02 22:49:59

标签: excel

我不知道为什么我得到的范围下标错误的了。当我单击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   

1 个答案:

答案 0 :(得分: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