Auto run two vba codes when an Excel workbook opens - excel

I have two VBA codes I would like to run when the Excel workbook is opened.
Sub test2()
Dim c As Range
For Each c In Range("A1:A1").Cells
c.Select
SendKeys "{F2}", True
SendKeys "{ENTER}", True
Next
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim xCell As Range
If Target.Address <> Range("A1").Address Then Exit Sub
Application.ScreenUpdating = False
For Each xCell In Range("B3:P3")
xCell.EntireColumn.Hidden = (xCell.Value < Target.Value)
Next
Application.ScreenUpdating = True
End Sub
It runs perfectly manually.
I have tried Sub Workbook_Open, but it does not work.
I have tried in module, in sheet and in ThisWorkbook too.
Could not make it work automatically as the workbook opens.
This code is supposed to F2+Enter cell A1 and then hide some columns depending on value in A1.
I modified code in this way:
Private Sub Workbook_Open()
test2
End Sub
Sub test2()
Dim c As Range
For Each c In Sheets("MySheet").Range("A1:A1").Cells
c.Select
SendKeys "{F2}", True
SendKeys "{ENTER}", True
Next
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim xCell As Range
If Target.Address <> Range("A1").Address Then Exit Sub
Application.ScreenUpdating = False
For Each xCell In Range("B3:P3")
xCell.EntireColumn.Hidden = (xCell.Value < Target.Value)
Next
Application.ScreenUpdating = True
End Sub
When openning worksheet it starts performing, does the first part (F2+Enter), but stops there. Does not perform this part:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim xCell As Range
If Target.Address <> Range("A1").Address Then Exit Sub
Application.ScreenUpdating = False
For Each xCell In Range("B3:P3")
xCell.EntireColumn.Hidden = (xCell.Value < Target.Value)
Next
Application.ScreenUpdating = True
End Sub
Code writen in Sheet1 (not "ThisWorkbook") manually performs well (not automatically).
The same code writen in "ThisWorkbook" starts performing automatically when file opens, but stops in the middle (as mentions earlier).

I think you're doing an over-engineering here.
Currently you want to:
Call on open Workbook_Open
... the macro test2 which simulates a change in the sheet (by pressing F2 and Enter), so that...
... the code inside Worksheet_Change gets called.
In fact, what you really want is to have the code that is now inside Worksheet_Change inside Workbook_Open.
So:
Remove test2
Remove the code from Worksheet_Change
Add your code directly inside Workbook_Open as follows:
Private Sub Workbook_Open()
Dim xCell As Range
Dim Target As Range: Set Target = Sheets("yourSheet").Range("A1")
Application.ScreenUpdating = False
For Each xCell In Sheets("yourSheet").Range("B3:P3")
xCell.EntireColumn.Hidden = (xCell.Value < Target.Value)
Next
Application.ScreenUpdating = True
End Sub

Related

Excel VBA combine two SUBs

Any chance of getting help combining the two below codes?
I'll try to educate myself on combining these things as I'm sure it's not that complicated, but for now I'd appreciate any assistance.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Application.CutCopyMode = False Then
Application.Calculate
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim UndoList As String
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
On Error GoTo ErrExit
UndoList = Application.CommandBars("Standard").Controls("&Undo").List(1)
If Left(UndoList, 5) = "Paste" Or UndoList = "Auto Fill" Then
MsgBox "Copy / paste is not permitted" & vbCr & _
"- Creator"
With Application
.Undo
.CutCopyMode = False
End With
Target.Select
End If
'The UperCase part______________________________________________
If Not (Application.Intersect(Target, Range("E8:OF57")) _
Is Nothing) Then
With Target
If Not .HasFormula Then
Application.EnableEvents = False
.Value = UCase(.Value)
Application.EnableEvents = True
End If
End With
End If
'_______________________________________________________________
ErrExit:
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
I'm trying to make my workbook as easy to use as possible, and to avoid user mistakes that mess upp formulas and so forth.
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Dim MyPicture As Object
Dim MyTop As Double
Dim MyLeft As Double
Dim TopRightCell As Range
'-----------------------------------------------------------
'- top right cell
With ActiveWindow.VisibleRange
r = 1
c = .Columns.Count
Set TopRightCell = .Cells(r, c)
End With
'------------------------------------------------------------
'- position picture
Set MyPicture = ActiveSheet.Pictures(1)
MyLeft = TopRightCell.Left - MyPicture.Width - 200
With MyPicture
.Left = MyLeft
End With
End Sub
The line starting with Private Sub or Sub begins the macro, and the line End Sub is the end of the macro.
Of the two code blocks you've pasted, the top contains two macros (one Worksheet_SelectionChange and one Worksheet_Change), and the second block only contains a SelectionChange one.
Depending which of those you wish to merge, just cut-paste the code from the inside of one sub (i.e. not including the start and end lines Private Sub and End Sub) into another, to make an amalgamated sub containing both sets of code. You may wish to amalgamate all three, but I'd guess it's just the two SelectionChange subs you want to merge.

Excel VBA Worksheet_Change for a Range of values

I have a problem with VBA, I need to use the worksheet change event to pickup cell values from AI28 to AI30 and move them over to V28 to V30. This is what I have do so far
Private Sub Worksheet_Change(ByVal Target As Range)
If IsNumeric(Target) And Not (Target = "") Then
If Target.Address = Range("AI28:AI30").Address Then
Range("V28:V30").Value = Range("AH28:AH30").Value
Else
If Target.Cells.Value <> Empty Then Exit Sub
Exit Sub
End If
End If
End Sub
It works fine for just one range eg AI28 and V28 so what am I missing? A loop or something?
Use a loop and Intersect:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Set rng = Intersect(Target, Me.Range("AI28:AI30"))
If rng Is Nothing Then Exit Sub
On Error GoTo SafeExit
Application.EnableEvents = False
Dim cell As Range
For Each cell In rng
If IsNumeric(cell.Value) And Not IsEmpty(cell.Value) Then
Me.Range("V" & cell.Row).Value = cell.Value
End If
Next
SafeExit:
Application.EnableEvents = True
End Sub

Restrict Worksheet_Change to a specified range of cells

I want to record a list of live data in a separate sheet.
Found this code online which works.
How to do I change the range from one cell A1 to a Range A1:D30?
Private Sub Worksheet_Change(ByVal Target As Range)
Dim dest As Range
Application.EnableAnimations = False
On Error GoTo line1
If Target.Address <> "$A$1" Then GoTo line1
Set dest = Worksheets("sheet2").Cells(Rows.Count, "a").End(xlUp).Offset(1, 0)
'MsgBox dest.Address
Target.Copy dest
line1:
Application.EnableEvents = True
End Sub
This can be done without a custom function. VBA already contains all you need.
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:D30")) Is Nothing Then
' run some code
End If
End Sub

Make cell-contents uppercase on value change

I'm not experienced in VBA and I've pieced together a small script to make the contents of a cell uppercase once any value has been entered. The script should apply this only to a certain range of cells, in my case J11:AK25.
The script works (it makes the contents of a cell uppercase once something is entered or changed), but Excel crashes right after entering or changing a value. This happens in Excel 2013.
The code I have right now:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("J11:AK24")) Is Nothing Then RunUp
End Sub
Sub RunUp()
Range("J11:AK25") = [index(upper(J11:AK25),)]
End Sub
Anyone able to assist?
turn off the events before calling the other sub:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Goto SafeOut
Application.EnableEvents = False
If Not Intersect(Target, Me.Range("J11:AK24")) Is Nothing Then RunUp
SafeOut:
Application.EnableEvents = True
End Sub
That being said, this may be safer:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo SafeOut
Application.EnableEvents = False
Dim rng As Range
Set rng = Intersect(Target, Me.Range("J11:AK24"))
If Not rng Is Nothing Then
Dim cel As Range
For Each cel In rng
cel.Value = UCase$(cel.Value)
Next cel
End If
SafeOut:
Application.EnableEvents = True
End Sub

Don't run Sub Worksheet_Change(ByVal Target As Range) after all cells in the worksheet has been cleared

I have a macro where i import a text file and update some elements of this file using the macro and then re-create the text file with the updated elements. I am validating some of the cells in a particular worksheet (USERSHEET)to make sure the user entries are correct and using the below Sub:
Option Explicit
Public Rec_Cnt As Integer
Private Sub Worksheet_Change(ByVal Target As Range)
Rec_Cnt = Sheets("MD").Cells(3, 7)
Dim Rng1 As Range
Dim Rng2 As Range
Dim Rng3 As Range
Set Rng1 = Range("E2:E" & Rec_Cnt)
Set Rng2 = Range("K2:K" & Rec_Cnt)
Set Rng3 = Range("Q2:Q" & Rec_Cnt)
If Not Application.Intersect(Target, Rng1) Is Nothing Then
If Len(Target) > 10 Then
Call Original_Ticket_Error
Exit Sub
End If
ElseIf Not Application.Intersect(Target, Rng2) Is Nothing Then
If Len(Target) > 10 Then
Call Original_Cnj_Ticket_Error
Exit Sub
End If
ElseIf Not Application.Intersect(Target, Rng3) Is Nothing Then
If Len(Target) > 10 Then
Call Original_Ticket_Error
Exit Sub
End If
End If
End Sub
Sub Original_Ticket_Error()
MsgBox "Original Ticket Number is more 10 characters"
End Sub
Sub Original_Cnj_Ticket_Error()
MsgBox "Original Conj. Ticket Number is more 10 characters"
End Sub
===============================================================================
Once the text file is created with the updated columns I am clearing all the cells in the USERSHEET.
However, I get a run-time error '13' for type mismatch
I wanted to check how can I avoid calling the Private Sub Worksheet_Change(ByVal Target As Range) after the worksheet(USERSHEET) is cleared
Any help is much appreciated.
Thanks,
sachin
Edit:
Code used to clear usersheet:
Sub Clear_User_Sheet()
Sheets("UserSheet").Select
Range("A2:R100002").Select
Application.Wait (Now + TimeValue("0:00:01"))
Selection.Delete
Application.EnableEvents = False
Application.Wait (Now + TimeValue("0:00:01"))
Selection.Delete
Selection.Delete
Sheets("Control Panel").Select
End Sub
Try this version of Clear_User_Sheet instead:
Sub Clear_User_Sheet()
Application.EnableEvents = False
Sheets("UserSheet").Range("A2:R100002").Delete
Application.EnableEvents = True
End Sub
PS. If you've used the code that you suggested in your edited answer, you may well find that EnableEvents is currently set to False - you'll want to correct that before running anything else.

Resources