列出打开的工作簿减去当前工作簿

时间:2015-10-19 18:04:58

标签: excel vba excel-vba combobox

我已经实现了以下代码,列出了ComboBox中所有打开的工作簿的名称:

Option Explicit
Private Sub ComboBox1_Change()
If Me.ComboBox1.ListIndex < 0 Then
Me.CommandButton2.Enabled = False
Else
Me.CommandButton2.Enabled = True
End If
End Sub

Private Sub CommandButton1_Click()
Unload Me
End Sub
Private Sub CommandButton2_Click()
MsgBox "Are you sure you want to select " & Me.ComboBox1.BoundValue, vbOKOnly
Application.Workbooks(Me.ComboBox1.Value).Activate
End Sub
Private Sub UserForm_Initialize()

Dim myWin As Window
Dim wkbk As Workbook

With Me.ComboBox1
.Style = fmStyleDropDownList
End With

With Me.CommandButton1
.Caption = "Cancel"
.Enabled = True
.Cancel = True
.TakeFocusOnClick = False
End With

With Me.CommandButton2
.Enabled = False
.Default = True
.Caption = "Activate Workbook"
.TakeFocusOnClick = False

End With

Me.Caption = "Please select a workbook"

For Each wkbk In Application.Workbooks
For Each myWin In wkbk.Windows
If myWin.Visible = True Then
Me.ComboBox1.AddItem wkbk.Name

Exit For
End If
Next myWin
Next wkbk

End Sub

这很好用,但也列出了列表顶部的当前工作簿。有没有办法可以从列表中排除当前的工作簿?

我尝试在ComboBox下拉单击事件上实现以下功能,但没有太多运气。

ComboBox1.RemoverItem ("Workbook.xls")

干杯

1 个答案:

答案 0 :(得分:1)

根据我的评论。

For Each wkbk In Application.Workbooks
If not wkbk.name =thisworkbook.name then
For Each myWin In wkbk.Windows
If myWin.Visible = True Then
Me.ComboBox1.AddItem wkbk.Name
Exit For
End If
Next myWin
end if
Next wkbk