Home » excel » Excel 2010 VBA running in all opened files

Excel 2010 VBA running in all opened files

Posted by: admin April 23, 2020 Leave a comment


I have one excel file (*.xlsm) with VBA code on first sheet:

Private Sub Worksheet_Calculate()
ActiveSheet.ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
End Sub

And second excel file with macro that is changing value in cell in first excel (it is automaticaly recalculated) and then copy value of new result from first excel and paste it to second excel file.

Problem is: when macro is going to second excel and paste value, worksheet is recalculated and code from first excel is calling, but it stops with error because in second excel it cant find chart object “Podtlak”.

How to set worksheet_calculate() to run only for file whitch one is it written?

How to&Answers:

Try specifying the workbook:

ThisWorkbook.ActiveSheet.ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value

Or specifying the worksheet and workbook:

ThisWorkbook.Worksheets("yourWorksheetName").ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value

I like the 2nd option best as you are clearly specifying the worksheet and workbook that this function runs on. Anytime you use ActiveSheet or ActiveWorkbook, you are relying on the fact that your intended worksheet is active when the code runs.