vba用userform替换msgbox

时间:2014-04-26 16:21:04

标签: excel-vba vba excel

我正在尝试用userform替换msgbox,但是当我显示userform时,它在文本框中没有像msgbox中那样的数据,我是否需要在文本框中添加一些代码?这就是我所做的

Sub unknown()
    Dim iListCount As Integer
    Dim iCtr As Integer



    ' Turn off screen updating to speed up macro.
    Application.ScreenUpdating = False

    ' Get count of records to search through (list that will be deleted).
    iListCount = Sheets("sheet2").Cells(Rows.Count, "A").End(xlUp).Row

    ' Loop through the "master" list.
    For Each x In Sheets("Sheet1").Range("A1:A" & Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row)
    ' Loop through all records in the second list.
        For iCtr = iListCount To 1 Step -1
            ' Do comparison of next record.
            ' To specify a different column, change 1 to the column number.
            If x.Value = Sheets("Sheet2").Cells(iCtr, 1).Value Then
                ' If match is true then delete row.
                Sheets("Sheet2").Cells(iCtr, 1).EntireRow.Delete
            End If
        Next iCtr
    Next
    Application.ScreenUpdating = True
    If Application.WorksheetFunction.CountA(Range("A:A")) = 0 Then
        Exit Sub
    End If
    For Each r In Intersect(Range("A:A"), ActiveSheet.UsedRange)
        If r.Value > "" Then
            msg = msg & vbCrLf & r.Value
        End If
    Next r
    ' this msgbox works ok
    'MsgBox msg, vbOKOnly, "Unknown servers"

    frmunknownservers.Show
    Textunknownservers.Text = msg

End Sub

1 个答案:

答案 0 :(得分:1)

我猜猜Textunknownservers是表单中Label的名称?您需要使用其所在的表单对其进行限定。此外,您需要在显示表单之前设置文本,除非您在表单上将ShowModal设置为false。否则,在用户关闭表单之前,文本将不会被设置。

frmunknownservers.Textunknownservers.Text = msg
frmunknownservers.Show

为了更好地封装,您可以在表单中创建一个方法来显示表单并显示消息。这个Sub将以你的形式代码:

Public Sub ShowWithMessage(msg As String)
    Textunknownservers.Text = msg
    Me.Show
End Sub

然后要显示你的表格,你会写下来。

frmunknownservers.ShowWithMessage "Hello, world"