我使用下面的代码将 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
代码运行后工作表可以更新/刷新吗?
最佳答案
即使表单打开并执行某些操作,工作表也应该更新。请参阅下面的最小示例(包含一个 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
- 因此需要注意这一点。
关于vba - 从列表框写入后刷新工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41802069/