从ListBox写入后刷新工作表

时间:2017-01-23 08:39:41

标签: vba excel-vba listbox refresh updates

我正在使用以下代码将项目从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

运行代码后可以更新/刷新工作表吗?

1 个答案:

答案 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

截图:

enter image description here

在您的代码中,当您重新启用ScreenUpdating时尚不清楚 - 因此需要注意这一点。