运行时错误91对象变量或在显示userform时未设置块变量

时间:2016-12-06 11:32:56

标签: excel-vba runtime-error userform vba excel

我关闭一个用户窗体并转到下一个有问题。单击命令按钮后,应关闭UserForm3,并显示UserForm4。不幸的是,我得到"运行时错误91对象变量或没有设置块变量"。我已深入挖掘互联网,我很确定问题出在Userform4上,尽管UserForm3的代码突出显示为错误。基本上我希望显示UserForm4并让所有文本框都填充来自sheet" Log"的数据,基于UserForm3中Combobox的选择。 UserForm3的选择保存到" Log"片。

来自UserForm3的代码

Private Sub CommandButton1_Click()

Sheets("Log").Range("E1") = ComboBox2.Text
Unload Me
UserForm4.Show  <- ERROR DISPLAYED HERE

End Sub

UserForm4我希望在下面的单元格中找到E1中的值,然后在Userform4中的填充文本框中找到来自该行的数据,其中找到了E1值。

UserForm4的代码

Private Sub UserForm_Initialize()

Dim Name As String
Dim rng As Range
Dim LastRow As Long
Dim wart As Worksheet

wart = Sheets("Log").Range("E1")
LastRow = ws.Range("B3" & Rows.Count).End(xlUp).Row + 1

Name = Sheets("Log").Range("E1")
UserForm4.TextBox8.Text = Name

nazw = Application.WorksheetFunction.VLookup(wart, Sheets("Log").Range("B3:H" & LastRow), 1, False)

UserForm4.TextBox1.Text = ActiveCell.Offset(, 1)
UserForm4.TextBox2.Text = ActiveCell.Offset(, 1)
UserForm4.TextBox3.Text = ActiveCell.Offset(, 1)
UserForm4.TextBox4.Text = ActiveCell.Offset(, 1)
UserForm4.TextBox5.Text = ActiveCell.Offset(, 1)
UserForm4.ComboBox1.Text = ActiveCell.Offset(, 1)
UserForm4.TextBox6.Text = ActiveCell.Offset(, 1)
UserForm4.TextBox7.Text = ActiveCell.Offset(, 1)

End Sub

1 个答案:

答案 0 :(得分:0)

下面的代码是为了避免上面代码中提到的运行时错误,它没有针对VLookup函数部分进行调试。

Option Explicit

Private Sub UserForm_Initialize()

Dim Name        As String
Dim LastRow     As Long
Dim wart        As Variant
Dim ws          As Worksheet
Dim nazw        As Long

' set ws to "Log" sheets
Set ws = Sheets("Log")

With ws
    wart = .Range("E1")

    ' method 1: find last row in Column "B" , finds last row even if there empty rows in the middle
    LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row + 1

    ' method 2 to find last row, equivalent to Ctrl + Shift + Down
    ' LastRow = .Range("B3").CurrentRegion.Rows.Count + 1

    ' a little redundant with the line 2 above ?
    Name = .Range("E1")
End With

With Me
    .TextBox8.Text = Name

    ' ****** Need to use Match instead of Vlookup VLookup Section ******
    If Not IsError(Application.Match(wart, ws.Range("B1:B" & LastRow - 1), 0)) Then
        nazw = Application.Match(wart, ws.Range("B1:B" & LastRow - 1), 0)
    Else ' wart record not found in range
        MsgBox "Value in Sheet " & ws.Name & " in Range E1 not found in Column B !", vbInformation
        Exit Sub
    End If

    .TextBox1.Text = ws.Range("B" & nazw).Offset(, 1)
    .TextBox2.Text = ws.Range("B" & nazw).Offset(, 1)
    .TextBox3.Text = ws.Range("B" & nazw).Offset(, 1)
    .TextBox4.Text = ws.Range("B" & nazw).Offset(, 1)
    .TextBox5.Text = ws.Range("B" & nazw).Offset(, 1)
    .ComboBox1.Text = ws.Range("B" & nazw).Offset(, 1)
    .TextBox6.Text = ws.Range("B" & nazw).Offset(, 1)
    .TextBox7.Text = ws.Range("B" & nazw).Offset(, 1)
End With

End Sub