Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have a bug about call a macro in excel that need your help.

I wrote a macro setColor() to set background color and set value to sheet1 of excel file A, end then at excel file B, I called this macro of file A, But there a bug.

in excel 2003 my code only can set value and can't not set background color for file A, althought this macro run OK when called at file A.

in the case, I open both file A and file B by excel 2007 , it run OK.
So do My code have any problem? and How to My macro can run at both excel 2003 and 2007 even excel 2010?
this is may code:
file A(calMacroOtherFile.xls):
VB
Public Sub setColor()
    With Workbooks(Application.ThisWorkbook.Name).Worksheets("Sheet1")
        .Range(.Cells(3, 5), .Cells(6, 5)).Interior.ColorIndex = 3
        .Cells(3, 4).Interior.ColorIndex = 15
        .Cells(3, 4).Value = "ckfjfio"
        MsgBox "Workbook Name: " & workBookName
    End With
End Sub


file B:
VB
Private Sub CommandButton1_Click()
    On Error GoTo ErrorCode
    Application.Run ("'calMacroOtherFile.xls'!setColor()")
    Exit Sub
ErrorCode:
    MsgBox "Error discription: " & Err.Description

End Sub



Thank in advance
Posted

1 solution

Instead ThisWorkbook[^] use ActiveWorkbook[^] and everything should be OK. Follow the links to understand the difference.

Example:
VB
Public Sub setColor()
    With ActiveWorkbook.Worksheets("Sheet1")
        .Range(.Cells(3, 5), .Cells(6, 5)).Interior.ColorIndex = 3
        .Cells(3, 4).Interior.ColorIndex = 15
        .Cells(3, 4).Value = "ckfjfio"
    End With
End Sub


In above example the color of cells is changing for active workbook. If there are 3 workbooks opened, then changes are made only for active workbook. If you change the active workbook and then execute macro, changes are made for actually active workbook.
Try this
VB
Private Sub ChangeColorOfCellsForEachWbk()
    For each wbk in Application.Workbooks
        setColor()
    Next
End Sub


To call macro from vbscript, see these:
http://stackoverflow.com/questions/2050505/way-to-run-excel-macros-from-command-line-or-batch-file[^]
http://stackoverflow.com/questions/10881951/how-to-launch-an-excel-macro-from-command-line-without-worksheet-open-event[^]
 
Share this answer
 
v2
Comments
ngthtra 15-Jul-13 0:10am    
So How to call this macro on CMD on Window?
Maciej Los 15-Jul-13 5:30am    
See my answer now ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900