2016-08-02 145 views
0

我試圖從用戶窗體插入圖像到excel工作表,但如果當我按窗體上的提交按鈕時沒有選擇圖片它說運行時錯誤'424':所需的對象。我怎麼解決這個問題? 以下是瀏覽按鈕。在vba中插入圖像

Private Sub browse_Click() 
Dim pic As Variant 
pic = Application.FileDialog(msoFileDialogFilePicker) 
With pic 

    .AllowMultiSelect = False 
    .ButtonName = "Submit" 
    .Title = "Select an image file" 
    .Filters.Add "Image", "*.gif;*.jpg;*.jpeg", 1 
    If .Show = -1 Then 



      Me.filepath.Text = .SelectedItems(1) 
      Me.picpreview.PictureSizeMode = fmPictureSizeModeClip 
      Me.picpreview.Picture = LoadPicture(.SelectedItems(1)) 


    Else 


    End If 

    If pic = False Then Exit Sub 

End With 




End Sub 

而以下是將圖像分配給特定單元的代碼。

Cells(emptyrow, 10).Select 
With xlApp.ActiveSheet.Pictures.Insert(picname) 'it is this line the debugger always points to when I submit the form without a picture 
    With .ShapeRange 
     .LockAspectRatio = msoTrue 
     .Height = 150 
    End With 
    .Left = xlApp.ActiveSheet.Cells(emptyrow, 10).Left 
    .Top = xlApp.ActiveSheet.Cells(emptyrow, 10).Top 
    .Placement = 1 
    .PrintObject = True 
End With 
+0

在做任何事之前檢查選定的項數。 –

回答

0

這應該畫面窗體和插入工作,主要的改變是我們DimOffice.FileDialog的窗口選取器和分離選擇畫面和設置,而不是使用圖片對象,我們簡單地使用路徑。您需要調整_Click名稱。

Public PicPath As String 'this is where we'll store the picture path 

Private Sub Browse_Click() 'getting the picture path 

Dim fDialog As Office.FileDialog 
Set fDialog = Application.FileDialog(msoFileDialogFilePicker) 

With fDialog 

    .AllowMultiSelect = False 
    .ButtonName = "Submit" 
    .Title = "Select an image file" 
    .Filters.Add "Image", "*.gif;*.jpg;*.jpeg", 1 

    If .Show = -1 Then 
     PicPath = .SelectedItems(1) 
     'getting picture full path to use when submit click 
    End If 

    If PicPath = "" Then Unload Me 

End With 

End Sub 

Private Sub Submit_Click()'setting picture in active cell 

    If Not PicPath = "" Then 
     CellAddress = ActiveCell.Address 
     With ActiveSheet.Pictures.Insert(PicPath) 
      With .ShapeRange 
       .LockAspectRatio = msoTrue 
       .Height = 150 
      End With 
      .Left = ActiveSheet.Range(CellAddress).Left 
      .Top = ActiveSheet.Range(CellAddress).Top 
      .Placement = 1 
      .PrintObject = True 
     End With 
     picselectedbool = True 
    Else 
     msgbox ("Please select a picture") 
    End If 

    If picselectedbool Then 
     Unload Me 
    End If 

End Sub 
+0

非常感謝你!當我將代碼放入提交按鈕時,代碼就可以工作,但是現在它已經改變爲即使在我點擊提交後沒有選擇圖片時也會自動出現一張圖片。它可以解決使用錯誤報表? –

+0

嗨,我以爲你的目標是將圖片插入Excel表格中,MB。你能準確地告訴我你期望的圖片插入的行爲嗎(就像打開圖片和插入它之間發生的事情一樣?),因爲我認爲我誤解了它。 @白羽ルカ –

+0

我期望的是,我可以通過用戶窗體選擇圖片,並且一旦我按下了用戶窗體上的提交按鈕,它就會自動將圖片插入到我想要的目標窗格中。對困惑感到抱歉。 @Miguel_Ryu –