我不知道为什么我得到的范围下标错误的了。当我单击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
答案 0 :(得分:0)
您正在混淆变量ws
和xWs
。
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
将返回TRUE
或FALSE
。结果决定了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