2016-12-10 98 views
0

我在vba表單上有3張圖片。
圖像是(picture1,picture2和selectedImage)問題設置VBA表單上圖像的圖片屬性

VBA設置picture1或picture2等於selectedImage。 Picture1和Picture2初始化爲(無),並將selectedImage設置爲本地位文件。

Private Sub updatePicture(position As Integer) 

'This code works when un-commented out and run 
    'Picture1.Picture = selectedImage.Picture 

'This code does not update the images 
    If position = 1 Then 
     Picture1.Picture = selectedImage.Picture 
    ElseIf position = 2 Then 
     Picture2.Picture = selectedImage.Picture 
    End If 

End Sub 

我調試和確認位置= 1,行「Picture1.Picture = selectedImage.Picture」正在運行,但圖像沒有正在更新中...

任何幫助將受到歡迎。使用excel 2013.

+0

請更新您的問題,以澄清是否Image控件被稱爲'selectedPicture'或'selectedImage'。 –

+0

對不起,混亂,代碼是正確的...圖像控件selectedImage –

回答

0

這種類型的問題通常與更改爲Image圖片不會觸發事件有關。假設你肯定將1或2傳入程序(你應該檢查確定你是否是),有幾種方法可以處理重繪問題:

一種方法是將Repaint方法添加到你的代碼的下方,這樣你的程序應爲:

If position = 1 Then 
    Picture1.Picture = selectedImage.Picture 
ElseIf position = 2 Then 
    Picture2.Picture = selectedImage.Picture 
End If 
Me.Repaint 

然而,這將重繪整個Userform,並可能導致閃爍,如果你正在快速更新畫面(如進度監視器或多次點擊操作上)或有一個巨大的Userform

另一種方式是創建一個事件並通過該事件運行新照片。我不能從權威的角度說這個,但我的印象是,Event將強制重繪,並且似乎只是刷新Userform中檢測到更改的部分,所以我的經驗是這種方法非常流暢。

你這樣做的方式非常簡單。你插入一個新的Class並適當命名它(我叫我的clsPicHandler)。該類中的代碼可能是有點,因爲這:

Option Explicit 
Public Event PictureChanged(img As MSForms.Image, pic As Object) 

Public Sub SetPicture(img As MSForms.Image, pic As Object) 

    If img Is Nothing Or pic Is Nothing Then Exit Sub 
    If img.Picture Is pic Then Exit Sub 

    RaiseEvent PictureChanged(img, pic) 

End Sub 

的代碼背後的Userform的話,會引發和處理事件,像這樣:

Option Explicit 

Private WithEvents mPicHandler As clsPicHandler 

Public Sub UpdatePicture(position As Integer) 
    If position = 1 Then 
     mPicHandler.SetPicture Picture1, selectedImage.Picture 
    ElseIf position = 2 Then 
     mPicHandler.SetPicture Picture2, selectedImage.Picture 
    End If 

End Sub 

Private Sub mPicHandler_PictureChanged(img As MSForms.Image, pic As Object) 
    img.Picture = pic 
    DoEvents 
End Sub 

Private Sub UserForm_Initialize() 
    Set mPicHandler = New clsPicHandler 
End Sub