2017-09-15 655 views
0

我有一個用戶窗體並點擊它應該訪問或打開一個用戶窗體的按鈕。但每次代碼獲取該部分,用戶窗體運行時錯誤'424':需要的對象Excel VBA

運行時錯誤 '424': 所需的對象

彈出。這裏是我的代碼:

If CheckSheet(TextBoxValue) = True Then 
     Sheets(TextBoxValue).Select 
     UserForm.Show 
    Else 
     Set Worksheet = ThisWorkbook.Sheets.Add(After:=Sheets(Sheets.Count)) 
     Worksheet.Name = TextBoxValue 

     Dim label As Control 
     For Each label In UserForm.Controls 
      If TypeName(label) = "Label" Then 
       With ActiveSheet 
        i = i + 1 

        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
        .Cells(lastRow, i).Value = label.Caption 
       End With 
      End If 
     Next 

     UserForm.Show 
    End If 

每次它獲取到部分與UserForm.ShowFor Each label In UserForm.Controls

我檢查形式的拼寫已經多次,這是大同小異。

+1

你有「選項顯式」設置嗎? – FunThomas

+0

它確實拼寫爲'UserForm'?創建的第一個表單通常稱爲「UserForm1」。編輯:忘記那個...只是讀你的文章的最後一行。 :) –

+0

在代碼的第一行和'F8'中放入一個「STOP」,直到發生錯誤。這應該縮小它的範圍。 – CLR

回答

0

你可能有這樣的事情在腦海: -

Sub TestCode() 

    Dim Ws As Worksheet     ' "Worksheet" is a reserved word 
    Dim MyForm As UserForm1    ' "UserForm" is a reserved word 
    Dim MyLabel As Control    ' "Label" is a reserved word 
    Dim C As Long      ' better name for a column than "i" 

    Set MyForm = New UserForm1 
    If GetSheet(Ws) Then 
     For Each MyLabel In MyForm.Controls 
      If TypeName(MyLabel) = "Label" Then 
       With Ws     ' true, Ws is the ActiveSheet but 
             ' always use the same name for the same sheet 
        C = C + 1 

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
        .Cells(LastRow, C).Value = MyLabel.Caption 
       End With 
      End If 
     Next 
    End If 
    MyForm.Show 
End Sub 

Private Function GetSheet(Ws As Worksheet) As Boolean 
    ' return True if Ws didn't exist 

    Dim Ws As Worksheet 

    On Error Resume Next 
    Set Ws = Worksheets(TextBoxValue) 
    If Err Then      ' Err = doesn't exist 
     Set Ws = ThisWorkbook.Sheets.Add(After:=Sheets(Sheets.Count)) 
     Ws.Name = TextBoxValue 
     GetSheet = True 
    End If 
End Function 

Private Function TextBoxValue() As String 
    TextBoxValue = "MySheetName" 
End Function 

爲了測試一個詞是「保留」的話,在你的VB編輯器,然後按F1選擇它。如果MS Office使用它,不要爭論。

+0

嗨,我有不同的工作簿中的不同用戶窗體中的代碼,它正在工作。我只是複製那些不同工作簿中的代碼。唯一的區別是我修改了我目前正在處理的用戶窗體上的控件。我的問題可能與我的用戶表單上的修改有關嗎?謝謝。 –

+0

一旦你開始使用保留字它不可能說出效果,而且通常不會。但是,即使在同一臺計算機上的同一工作簿上運行相同版本的MS Office和相同版本的Windows,VBA也不會每次都以完全相同的方式工作。是的,這可能是您所做的修改,但我的(瘋狂)猜測是您可能同時打開了兩個工作簿,即新建工作簿和您從中複製的工作簿。關閉一個將無濟於事。一旦VBA知道錯誤發生在哪裏,它會一直指向它發現的內容。 – Variatus

相關問題