Changing Excel Icon doesn't work when another

2019-09-11 07:59发布

问题:

I am using the following code, which nicely changes the Excel icon to my own icon.

It works perfectly as far as I open the workbook by itself BUT, as soon as another workbook is already opened, the code doesn't seem to have any effect any longer. It only works if Excel is completely closed, then I open the workbook with the code. As soon as I open another workbook, change from one workbook to another, etc, it not longer works.

I am using Windows 7, Excel 2007.

I hope someone can help. Thanks

Private Sub Workbook_Open()    
    changeXLIcon "D:/myBOOK/IQS.ico"
End Sub

Private Sub Workbook_WindowActivate(ByVal Wn As Window)
    changeXLIcon "D:/myBOOK/IQS.ico"
End Sub

Private Sub Workbook_WindowDeactivate(ByVal Wn As Window)
    changeXLIcon "Excel.exe"
End Sub


Declare Function GetActiveWindow32 Lib "USER32" Alias "GetActiveWindow" () As Integer
Declare Function SendMessage32 Lib "USER32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Declare Function ExtractIcon32 Lib "SHELL32.DLL" Alias "ExtractIconA" (ByVal hInst As Long, ByVal lpszExeFileName As String, ByVal nIconIndex As Long) As Long

Public Sub changeXLIcon(iconname As String)

    Dim Icon&


    Icon = ExtractIcon32(0, iconname, 0)
    SendMessage32 GetActiveWindow32(), &H80, 1, Icon '< 1 = big Icon
    SendMessage32 GetActiveWindow32(), &H80, 0, Icon '< 0 = small Icon


End Sub

回答1:

I'd guess that the problems stems from Excel having several processes running while you only set the icon for the current Window. Instead of just calling GetActiveWindow32() you should try to retrieve a list of all processes named EXCEL.EXE and then change the icon on all of them using SendMessage32 to their respective handle.



标签: excel vba icons