2个UserForm中已有代码如下,怎么修改:实现用户点击选择lstWorksheets列出的表名字时会跳到(显示)相应名字的表,方便用户查看。就是用户在UserForm1或2中选择表名后,Excel会切换到相应的工作表,但UserForm不会立即关闭,而是在用户点击确认按钮后才关闭. 请教能否实现?怎么改,谢谢 USERFORM2:
Private selectedWorksheet As Boolean
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
lstWorksheets.AddItem ws.Name
Next ws
End Sub Private Sub btnSelect_Click()
If lstWorksheets.ListIndex <> -1 Then
selectedWorksheet = True
Me.Hide
Else
MsgBox "请选择一个工作表。", vbExclamation
End If
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then ' 用户点击窗口右上角的关闭按钮
If Not selectedWorksheet Then
MsgBox "未选择数据来源表,无法进行复制。"
Cancel = True
End If
End If
End Sub
USERFORM1:
Private selectedWorksheet As Boolean
Private Sub UserForm_Initialize()
LoadWorksheetList ' 初始化时加载表名列表,代替下面4句,直接调用
' Dim ws As Worksheet
'For Each ws In ThisWorkbook.Worksheets
' lstWorksheets.AddItem ws.Name
'Next ws
End Sub Private Sub btnSelect_Click()
If lstWorksheets.ListIndex <> -1 Then
selectedWorksheet = True
Me.Hide
Else
MsgBox "请选择一个工作表。", vbExclamation
End If
End Sub
Public Sub LoadWorksheetList()
' 同名时重新加载表名列表--添加一个公共方法来加载表名列表
Me.lstWorksheets.Clear '清空列表框
' 添加工作表名到列表框
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
Me.lstWorksheets.AddItem ws.Name
Next ws
' 清除之前的选择
Me.lstWorksheets.ListIndex = -1
selectedWorksheet = False ' 重置选择标记
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then ' 用户点击窗口右上角的关闭按钮
If Not selectedWorksheet Then
MsgBox "未选择结果汇总呈现表,无法进行汇总。"
Cancel = True
End If
End If
End Sub
|