Calling a sub to another worksheet - vba

I have a sub that goes through each worksheet and checks for a flag.
If the flag is raised, I want it to run another sub. The flag checking works, but the other sub which is called runs on the main sheet.
Code:
Sub update()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If (ws.Cells(1, 5) = 1) Then
Call update2(ws)
End If
Next
End Sub
Sub update2(ws As Worksheet)
ws.clear <----does not work
End Sub
sub dothis()
cells(1,6) = "hallo"
end sub
how do I get this to work?

You need to either use a public variable (generally not recommended) or send the necessary arguments to the procedure(s) where they are needed.
Sub update2(ws As Worksheet)
Call dothis(ws)
End Sub
sub dothis(ws as Worksheet)
ws.cells(1,6) = "hallo"
end sub

Sub update2(ws As Worksheet)
ws.Cells.Clear
End Sub

Related

VBA Class Module as WorkSheet

Please consider the following "code":
Sub MySub()
Dim MySheet As Worksheet
Set MySheet = ActiveSheet
MySheet.DeleteAllRedWords 'This is a Sub
MsgBox MySheet.NumberOfChangesThisWeek 'This is a function
MySheet.ActiveOwner = "Sam" 'This is a property
End Sub
Is this possible? Would class modules do the trick? I tried the code below, but I got an error 438 (Object doesn't support this property or method). Is it possible somehow?
'CLASS MODULE CODE: MyWorkingSheet Class
Private Sub class_initialize()
Me = ActiveSheet
End Sub
'NORMAL MODULE CODE
Sub MySub()
Dim MyTodaySheet As MyWorkingSheet
Set MyTodaySheet = New MyWorkingSheet
End Sub
Sub MySub()
Dim MySheet As New MyWorkingSheet
Set MySheet.Sheet = ActiveSheet
MySheet.DeleteAllRedWords
'etc
End Sub
Class:
'CLASS MODULE CODE: MyWorkingSheet Class
Private m_sht As WorkSheet
'set a reference to the worksheet you want to "wrap" with your class
Property Set Sheet(sht As WorkSheet)
Set m_sht = sht
End Property
Sub DeleteAllRedWords()
'in all your class methods reference m_sht
With m_sht.UsedRange
'code to delete all red words
End With
End Sub
'other methods/functions

vba assigning sub routine to variable

I have the following sub routine (in module10).
Sub varWorksheet(wksht As String)
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(wksht)
Set ws = Nothing
End Sub
I want to be able to pass this sub routine as a reference to a variable with something like this rather than have to declare it explicitly in each routine:
Set ws = module10.varWorksheet("Sheet1")
I'm getting a compilation error -> expected Function or Variable.
You shoud use a function like this.
Function varWorksheet(wksht As String) As Worksheet
On Error Resume Next
Set varWorksheet = ThisWorkbook.Sheets(wksht)
End Function
It will return nothing if the worksheet doesn't exist. This works fine.
Sub Test()
Dim ws As Worksheet
Set ws = Modul10.varWorksheet("Tabelle4")
If ws Is Nothing Then
Debug.Print "No worksheet"
Else
' what ever you want
End If
End Sub

Applying Excel VBA code in a module to all worksheets

I've been struggling with this for a few days.
I have the below code which copies and pastes value when a certain If condition is met (the workbook has live data feeding into multiple sheets every second).
The code is currently located in a module, as the IF condition can apply to all sheets in the workbook.
The problem I have is the code only runs on the activesheet. I need it to run on all worksheets in the workbook. I've tried multiple loops with no success. Ideally I need the code to run across all sheets in the background (i.e. without activating them). Any help will be appreciated.
Dim TimeToRun
Sub auto_open()
Call SchedulePrices
End Sub
Sub SchedulePrices()
TimeToRun = Now + TimeValue("00:00:15")
Application.OnTime TimeToRun, "CopyPrice"
End Sub
Sub CopyPrice()
Calculate
If Range("AM7") = "1" Then
Range("AM10:AM69").Value = Range("K9:K68").Value
Range("AL10:AL69").Value = Range("B9:AM68").Value
Range("AM8:AM9").Value = Range("C2:C3").Value
End If
'run the timer sub
Call SchedulePrices
End Sub
Sub auto_close()
On Error Resume Next
Application.OnTime TimeToRun, "CopyPrice", , False
End Sub
Sub CopyPrice()
Dim sht as Worksheet
For Each sht in Worksheets
If sht.Range("AM7") = "1" Then
sht.Calculate
sht.Range("AM10:AM69").Value = sht.Range("K9:K68").Value
sht.Range("AL10:AL69").Value = sht.Range("B9:AM68").Value
sht.Range("AM8:AM9").Value = sht.Range("C2:C3").Value
End If
Next
'run the timer sub
Call SchedulePrices
End Sub

VBA closes another workbook when I only say 1

I have come across a strange glitch in a code that I found online. if I have two different spreadsheets open, one with this code in it and another that may well have no macros at all, and i leave that one alone for the specified time (as is the time I allow for in the macro) then the spreadsheet that has the macro in closes on me and then after the given time, the other spreadsheet closes too. Why does this happen?
Module 1:
Dim DownTime As Date
Sub SetTimer()
DownTime = Now + TimeValue("00:00:20")
Application.OnTime EarliestTime:=DownTime, _
Procedure:="ShutDown", Schedule:=True
End Sub
Sub StopTimer()
On Error Resume Next
Application.OnTime EarliestTime:=DownTime, _
Procedure:="ShutDown", Schedule:=False
End Sub
Sub ShutDown()
Application.DisplayAlerts = False
Call ExampleToSaveWorkbook
With ThisWorkbook
.Saved = True
.Close
End With
End Sub
Sub ExampleToSaveWorkbook()
'Saving the Workbook
bnam = ActiveWorkbook.Name
filenm = "S:\Economics\GTAA\dailyPM\excelfiles\backups\" & bnam
ActiveWorkbook.SaveAs filenm
End Sub
ThisWorkbook
Private Sub Workbook_Open()
Call SetTimer
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call StopTimer
End Sub
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
Call StopTimer
Call SetTimer
End Sub
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, _
ByVal Target As Excel.Range)
Call StopTimer
Call SetTimer
End Sub
Why is it closing more than the 1 workbook which has the macro?
The Shutdown sub calls ExampleToSaveWorkbook which closes the active workbook.
The remainder of the Shutdown then proceeds to close the ThisWorkBook object.

How to test an activesheet

Here is my code
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Set Sh = ActiveSheet
If ActiveSheet.Name = "Entrada" Then
Application.Calculation = xlManual
Else
Application.Calculation = x1automatic
End If
End Sub
but all the sheets is going to manual calculation, whats the error?
thx!
You are attempting to change the calculation at application level. I'm guessing you want to use
ActiveSheet.EnableCalculation = True ' or False
Just a thought on your Sh variable assignment. When Sh is passed into the Workbook_SheetActivate event macro, it is the worksheet being activated. You do not need to set it to the active sheet. The following will always report the name of the worksheet being newly activated to the Immediate window (including newly created worksheets).
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Debug.Print Sh.Name
End Sub
So your conditional statement could be tightened up to something like,
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If Sh.Name = "Entrada" Then
' do something here
Else
' do something else here
End If
End Sub
The values you set to Calculation should be: xlCalculationManualand xlCalculationAutomatic, not xlManual and x1automatic
See MSDN and this site http://www.cpearson.com/excel/optimize.htm