我有一个列表框,列表样式为单选按钮,行源设置为动态数据范围。
With SearchActionwordForm.SearchResultListBox
.ColumnCount = LastColumn - 1
.ListStyle = fmListStyleOption
.RowSource = DataRange
.Selected(0) = True
End With
根据用户输入的某些文本填充ListBox值。每次用户输入新的搜索文本时,数据范围都将被更改。在将新数据写入工作表之前,我有代码清除整个工作表。
Set ExcelAppl = CreateObject("Excel.Application")
Set wb = ActiveWorkbook
Application.DisplayAlerts = False
Set ws = wb.Worksheets(1)
ws.Cells.Clear
Dim rng As Range
'code to fetch data from Recordset
Set rng = ws.Range("A1")
lFieldCount = rs.Fields.Count
'copy record values starting from second row of the worksheet:
rng.Offset(1, 0).CopyFromRecordset rs
'Get the Last Column Number
Dim rLastCell As Range
Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
LastColumn = rLastCell.Column
LastColAdd = rLastCell.Address
LastCellCol = ExtractLetter(LastColAdd)
Set rLastCell = Nothing
'Get the Last Cell Address
Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
LastColumnAddress = rLastCell.Address
LastCellRow = ExtractNumber(LastColumnAddress)
LastColumnAddress = LastCellCol & LastCellRow
DataRange = "B2:" & LastColumnAddress
'Write headers to excel
For i = 0 To LastColumn - 1
rng.Offset(0, i).Value = rs.Fields(i).Name
Next i
wb.Save
“Ws.cells.clear”方法会触发我点击列表框时应该触发的“ListBox_Click”事件。
是否可以针对此特定情况禁止此事件?
答案 0 :(得分:1)
您最好避免.Rowsource填充任何列表框/组合框。 改为使用.list: 例如
listbox1.list=range("A1:K12").Value
答案 1 :(得分:0)
是否可以针对此特定情况抑制此事件?
是:定义一个全局布尔变量,当你执行ws.cells.clear
时, 除了 时总是为真 - 你在此之前将布尔值设置为false,然后回到真实。处理ListBox_Click
的例程将检查此布尔值是否为false,如果是,则不执行任何操作;否则它就是正常的事情。
如果出现任何其他不希望代码运行的情况,您可以使用此变量禁用ListBox_Click
处理。当您不希望进行处理的时间间隔结束时,请务必将布尔值恢复为True。