我想用UserForm填充一列。用户有4个选项如何填充列。我的问题是对的,只有第一种选择有效(2)。 单击OK按钮后,输入掩码也不会消失。应将所选选项复制到H列并自动填充。我的错误在哪里?
Private Sub CommandButton1_Click()
' OK Button
Dim emptyRow As Range
Dim lastrow As Long
lastrow = Cells.SpecialCells(xlCellTypeLastCell).row
Worksheets("Sheet1").Activate
Set emptyRow = Worksheets("Sheet1").Range("H2:H" & lastrow)
If OptionButton2.value = True Then
emptyRow.value = "2"
If OptionButton3.value = True Then
emptyRow.value = "3"
If OptionButton4.value = True Then
emptyRow.value = "4"
If OptionButton5.value = True Then
emptyRow.value = "5"
End If
End If
End If
End If
End Sub
答案 0 :(得分:0)
给出一个镜头..这里最大的区别是If statement
是如何写的。您的原始代码彼此嵌套If statements
,这很好,但不适用于您要实现的目标。我写的声明是 1 If statement
。另一种方法是通过Select Case
语句。为了便于学习,我将代码与原始代码保持一致。
Private Sub CommandButton1_Click()
' OK Button
Dim emptyRow As Range, ws As Worksheet
Dim lastrow As Long
Set ws = ThisWorkbook.Sheets(1)
lastrow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row 'A more flexible way to find last row
Set emptyRow = ws.Range("H2:H" & lastrow)
If OptionButton2.value = True Then
emptyRow.value = "2"
ElseIf OptionButton3.value = True Then
emptyRow.value = "3"
ElseIf OptionButton4.value = True Then
emptyRow.value = "4"
ElseIf OptionButton5.value = True Then
emptyRow.value = "5"
Else: MsgBox "No option was chosen.", vbOKOnly, "No Option Chosen" 'Catches no button selected
End If
Me.Hide 'This hides the userform. Another method is Unload Me which drops the cache as well
End Sub