我正在使用以下代码将项目从ListBox
添加到Sheet1
。一切正常,但点击“添加”后,工作表并不令人耳目一新。我只有在关闭表单时才会看到更改(添加的行)。
Private Sub btnAdd_Click()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim wbc As Workbook
Dim wsc As Worksheet
Set wbc = ActiveWorkbook
Set wsc = wbc.Worksheets("Sheet1")
Dim addme As Range
Dim x, y As Integer
Set addme = Application.Selection
For x = 0 To Me.lbsourceList.ListCount - 1
If Me.lbsourceList.Selected(x) Then
addme.Offset(1).EntireRow.Insert
wsc.Range(Cells(addme.Row, "C"), Cells(addme.Row, "C")).Offset(1).Value = Me.lbsourceList.List(x, 0)
wsc.Range(Cells(addme.Row, "I"), Cells(addme.Row, "I")).Offset(1).Value = Me.lbsourceList.List(x, 1)
Set addme = addme.Offset(1, 0)
End If
Next x
For y = 0 To Me.lbsourceList.ListCount - 1
If Me.lbsourceList.Selected(y) Then Me.lbsourceList.Selected(y) = False
Next y
End Sub
运行代码后可以更新/刷新工作表吗?
答案 0 :(得分:2)
即使表单已打开并执行某些操作,工作表也应更新。请参阅下面的最小示例(使用Userform
,一个Listbox
和一个CommandButton
):
Option Explicit
Private Sub CommandButton1_Click()
Dim lngCounter As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
For lngCounter = 0 To Me.ListBox1.ListCount - 1
ws.Cells(lngCounter + 1, 1).Value = Me.ListBox1.List(lngCounter, 0)
Next lngCounter
End Sub
Private Sub UserForm_Initialize()
Me.ListBox1.AddItem "foo"
Me.ListBox1.AddItem "bar"
Me.ListBox1.AddItem "baz"
End Sub
截图:
在您的代码中,当您重新启用ScreenUpdating
时尚不清楚 - 因此需要注意这一点。