I have an issue that makes no sense to me.
Option Explicit
Private Sub Worksheet_Calculate()
Dim Chtob As ChartObject
Dim wks As Worksheet
Set wks = ActiveSheet
On Error GoTo Terminate
For Each Chtob In ActiveSheet.ChartObjects
With Chtob.Chart
If wks.Range("$G$2").Value <> .Axes(xlCategory).MaximumScale Then
.Axes(xlCategory).MaximumScale = wks.Range("$G$2").Value
End If
If wks.Range("$C$2").Value <> .Axes(xlCategory).MinimumScale Then
.Axes(xlCategory).MinimumScale = wks.Range("$C$2").Value
End If
If wks.Range("$G$2").Value <> .Axes(xlCategory, xlSecondary).MaximumScale Then
.Axes(xlCategory, xlSecondary).MaximumScale = wks.Range("$G$2").Value
End If
If wks.Range("$C$2").Value <> .Axes(xlCategory, xlSecondary).MinimumScale Then
.Axes(xlCategory, xlSecondary).MinimumScale = wks.Range("$C$2").Value
End If
End With
Next
Exit Sub
Terminate:
MsgBox "Storm Event Not Valid, Please check if such event number exists"
End
Exit Sub
This macro is used on a tab that has two charts. When a certain cell changes the macro updates the graph scale. This tab will be then duplicated numerous times to show different time events.
The issue arises when someone else tries to open this file. The moment the file is open they get the error to pop up as many times as the amount of tabs created. This for some reason causes a different tab with a different graph to reset it's x scale. This different tab does not have the dynamic macro attached to it and no other macros are being used.
I want to say that a different version of Excel might be part of the problem, but there are times when this doesn't happen.
The way it should work is when somebody enters the wrong value in cell B2 the macro can't execute. So instead of going into debug, one gets an error message. So I need the error portion of the macro to be there.
I should mention that the tab also has another dynamic macro that automatically renames the tab name if the same cell changes.
Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B$2" Then
If Not Target.HasFormula Then
If Not Target.Value = vbNullString Then
On Error GoTo ErrHandler
ActiveSheet.Name = "Event" & " " & Target.Value
End If
End If
End If
Exit Sub
ErrHandler:
MsgBox "Error " & Err & ":" & Error(Err)
On Error GoTo 0
End Sub
Thanks to comments made by Scott, my issue has never poped up again
I just changed Set wks = Activesheet to Set wks = Me and then changed all of the wks to Me in the script
Option Explicit
Private Sub Worksheet_Calculate()
Dim Chtob As ChartObject
Dim wks As Worksheet
Set wks = Me
On Error GoTo Terminate
For Each Chtob In Me.ChartObjects
With Chtob.Chart
If wks.Range("$G$2").Value <> .Axes(xlCategory).MaximumScale Then
.Axes(xlCategory).MaximumScale = wks.Range("$G$2").Value
End If
If wks.Range("$C$2").Value <> .Axes(xlCategory).MinimumScale Then
.Axes(xlCategory).MinimumScale = wks.Range("$C$2").Value
End If
If wks.Range("$G$2").Value <> .Axes(xlCategory, xlSecondary).MaximumScale Then
.Axes(xlCategory, xlSecondary).MaximumScale = wks.Range("$G$2").Value
End If
If wks.Range("$C$2").Value <> .Axes(xlCategory, xlSecondary).MinimumScale Then
.Axes(xlCategory, xlSecondary).MinimumScale = wks.Range("$C$2").Value
End If
End With
Next
Exit Sub
Terminate:
MsgBox "Storm Event Not Valid, Please check if such event number exists"
End
End Sub
Related
I need some help. I am new to Excel VBA. I am trying to create a userform for stock inventory records and I been geting the automation error -2147467259. My problem is that the code works but after a few mouse clicks (10 or more) or after long usage, I keep getting this error. My code:
Private Sub cbPickID_Change()
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim tbl_issuance As ListObject
Set tbl_issuance = shIssuance.ListObjects("tblIssuance")
If Not tbl_issuance.DataBodyRange Is Nothing Then
tbl_issuance.DataBodyRange.Delete
End If
Dim tbl_pick As ListObject
Set tbl_pick = shPickList.ListObjects("tblPickList")
On Error GoTo ErrDetect
With tbl_pick.DataBodyRange
.AutoFilter field:=1, Criteria1:=Me.cbPickID.Value
End With
Dim pick_row As Long
pick_row = shPickList.Range("A" & Application.Rows.Count).End(xlUp).Row
shPickList.Range("A3:L" & pick_row).SpecialCells(xlCellTypeVisible).Copy
shIssuance.Range("A3").PasteSpecial (xlPasteValuesAndNumberFormats)
tbl_pick.AutoFilter.ShowAllData
Application.CutCopyMode = False
Dim issued_row As Long
issued_row = shIssuance.Range("A" & Application.Rows.Count).End(xlUp).Row
With Me.lbPickList
.ColumnHeads = True
.ColumnCount = 12
.ColumnWidths = ("40,40,40,110,0,45,40,60,90,0,0,0")
.RowSource = shIssuance.Range("A3:L" & issued_row).Address
End With
ErrDetect:
If Err.Number = 1004 Then
MsgBox "No records found!"
Exit Sub
End If
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
When I click debug, the error point at this
tbl_issuance.DataBodyRange.Delete
all my reference are in the same file. if I want to use the Excel VBA again, I need to close all Excel file and re-open them again.
any advice is highly appreciated.
I'm working on an Excel worksheet and using VBA to complete and update information on the cells.
There are seven columns in the Excel table. Three of them are drop-down lists with Data Validation, which I used the following VBA code to fill them.
Private Sub TempCombo_KeyDown(ByVal _KeyCode As MSForms.ReturnInteger, _ ByVal Shift As Integer)
'Ocultar caixa de combinação e mover a próxima célula com Enter e Tab
Select Case KeyCode
Case 9
ActiveCell.Offset(0, 1).Activate
Case 13
ActiveCell.Offset(1, 0).Activate
Case Else
'Nada
End Select
End Sub
These columns also work with autocomplete, using the code below:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim str As String
Dim cboTemp As OLEObject
Dim ws As Worksheet
Dim wsList As Worksheet
Set ws = ActiveSheet
Set wsList = Sheets(Me.Name)
Application.EnableEvents = False
Application.ScreenUpdating = False
If Application.CutCopyMode Then
'Permite copiar e colar na planilha
GoTo errHandler
End If
Set cboTemp = ws.OLEObjects("TempCombo")
On Error Resume Next
With cboTemp
.Top = 10
.Left = 10
.Width = 0
.ListFillRange = ""
.LinkedCell = ""
.Visible = False
.Value = ""
End With
On Error GoTo errHandler
If Target.Validation.Type = 3 Then
Application.EnableEvents = False
str = Target.Validation.Formula1
str = Right(str, Len(str) - 1)
With cboTemp
.Visible = True
.Left = Target.Left
.Top = Target.Top
.Width = Target.Width + 15
.Height = Target.Height + 5
.ListFillRange = str
.LinkedCell = Target.Address
End With
cboTemp.Activate
'Abrir a lista suspensa automaticamente
Me.TempCombo.DropDown
End If
errHandler:
Application.ScreenUpdating = True
Application.EnableEvents = True
Exit Sub
End Sub
Anytime I update any cell on a row, I want that the content of the seventh column of this row is updated with the current date.
I tried using the following code, but it only works with common cells, the ones that I manually type its content. I want the seventh column to be updated when I change the drop-down list selection also.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row = 1 Then Exit Sub
Application.EnableEvents = False
Cells(Target.Row, "U").Value = Date
End Sub
Is there any way to update the content of the column as I said before? Even when I change the option selected in the drop-down list?
Your code is fine except that you need to turn events back on. You have stopped events from firing with this line: Application.EnableEvents = False but you never turn the event firings back on again. So your code will work the first time you change a cell, the Worksheet_Change event will fire as expected. However, within this sub you have set EnableEvents to false and then never set it back to true. So you have stopped all future events, including this one, from firing again in the future. Here is the solution:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row = 1 Then Exit Sub
Application.EnableEvents = False
Cells(Target.Row, "U").Value = Date
Application.EnableEvents = True
End Sub
Edit: My real question is how to test if object was set that was instantiated. I am not really looking to "correct" my code. Its just an example.
I have a function that returns a workbook:
Edit: Added code
Sub GetWb() as Workbook
Application.DisplayAlerts = False
Application.EnableEvents = False
On Error Resume Next
Set wM = Application.Workbooks.Open("Z:\somepath.xlsm", ReadOnly:=True)
Application.EnableEvents = True
Application.DisplayAlerts = True
On Error GoTo 0
end sub
In another sub I want to check if that object was set properly by the function. I usually do something like this with objects generally:
dim w as Workbook
set w = GetWb
if w is nothing then
debug.print "no workbook"
else
debug.print "workbook"
end if
However, the is nothing test does not work because the object is instantiated, but was not set so it is something, not nothing.
I have resorted to this ugly solution, which works fine:
dim w as Workbook
set w = GetWb
on error goto someerrorhandling
if w.name = "" then
end if
on error goto 0
'other code here
someerrorhandling:
msgbox "no workbook"
In other words, I check a property of the object to force an error, or not. There must be a better/cleaner way.
I checked and this link states that the way I am doing it is the best way:
VBA: Conditional - Is Nothing
change your error handling for GetWB so it returns nothing incase of error, also use Function instead of sub.
Function GetWb() As Workbook
Application.DisplayAlerts = False
Application.EnableEvents = False
On Error GoTo errHandler:
Set GetWb = Application.Workbooks.Open("Z:\somepath.xlsm", ReadOnly:=True)
Application.EnableEvents = True
Application.DisplayAlerts = True
errHandler:
If Err.Number <> 0 Then
Set GetWb = Nothing
Application.EnableEvents = True
Application.DisplayAlerts = True
End If
End Function
Stackovwerflow community.
I do believe that this question was asked x1000 times here, but i just wasn not able to find a solution for my slow macro.
This macro serves for unhiding certain areas on worksheets if correct password was entered. What area to unhide depends on cell value. On Sheet1 i have a table that relates certain cell values to passwords.
Here's the code that i use.
1st. Part (starts on userform named "Pass" OK button click)
Private Sub CommandButton1_Click()
Dim ws As Worksheet
DoNotInclude = "PassDB"
For Each ws In ActiveWorkbook.Worksheets
If InStr(DoNotInclude, ws.Name) = 0 Then
Application.ScreenUpdating = False
Call Module1.Hide(ws)
Application.ScreenUpdating = True
End If
Next ws
End Sub
2nd Part.
Sub Hide(ws As Worksheet)
Application.Cursor = xlWait
Dim EntPass As String: EntPass = Pass.TextBox1.Value
If EntPass = Sheet1.Range("G1").Value Then ' Master-Pass, opens all
Sheet1.Visible = xlSheetVisible
ws.Unprotect Password:="Test"
ws.Cells.EntireRow.Hidden = False
Pass.Hide
Else
Dim Last As Integer: Last = Sheet1.Range("A1000").End(xlUp).Row
Dim i As Integer
For i = 2 To Last
Dim region As String: region = Sheet1.Range("A" & i).Value
Dim pswd As String: pswd = Sheet1.Range("B" & i).Value
If EntPass = pswd Then
ws.Unprotect Password:="Test"
ws.Cells.EntireRow.Hidden = False
Dim b As Integer
Dim Last2 As Integer: Last2 = ws.Range("A1000").End(xlUp).Row
For b = 2 To Last2
ws.Unprotect Password:="Test"
If ws.Range("A" & b).Value <> region Then
ws.Range("A" & b).EntireRow.Hidden = True
End If
If ws.Range("A" & b).Value = "HEADER" Then
ws.Range("A" & b).EntireRow.Hidden = False
End If
ws.Protect Password:="Test"
Next b
End If
Next i
End If
Application.Cursor = xlDefault
Sheet2.Activate
Sheet2.Select
Pass.Hide
End Sub
It works fast enough if I enter master-pass to get access to every hidden area, but if i enter cell.value related password, it takes about 5-6 minutes before macro will unhide required areas on every worksheet.
I'd be really grateful if someone could point out the reasons of slow performance and advise changes to be made in code. Just in case, i've uploaded my excel file here for your convenience.
http://www.datafilehost.com/d/d46e2817
Master-Pass is OPENALL, other passwords are "1" to "15".
Thank you in advance and best regards.
Try batching up your changes:
Dim rngShow as Range, c as range
ws.Unprotect Password:="Test" 'move this outside your loop !
For b = 2 To Last2
Set c = ws.Range("A" & b)
If c.Value = "HEADER" Then
c.EntireRow.Hidden = False
Else
If c.Value <> region Then
If rngShow is nothing then
Set rngShow = c
Else
Set rngShow=application.union(c, rngShow)
End If
End If
End If
Next b
If Not rngShow is Nothing Then rngShow.EntireRow.Hidden = False
ws.Protect Password:="Test" 'reprotect...
You might also want to toggle Application.Calculation = xlCalculationManual and Application.Calculation = xlCalculationAutomatic
You can also try moving your Application.Screenupdating code out of the loop, it's going to update for every sheet as written.
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Application.ScreenUpdating = False ''<- Here
DoNotInclude = "PassDB"
For Each ws In ActiveWorkbook.Worksheets
If InStr(DoNotInclude, ws.Name) = 0 Then
Call Module1.Hide(ws)
End If
Next ws
Application.ScreenUpdating = True ''<- Here
End Sub
I'm trying to transfer some code from one workbook to another and I'm having trouble figuring out why it's not working. I transferred the sheets into the new workbook and made the necessary updates in the code to reference the correct sheets. Everything else between the workbooks is consistent, but I keep receiving a compile error : User-defined type not defined. I tried debugging but I'm not sure what it's pointing to. Thanks in advance.
Sub CreatePP()
Dim ppApp As Object
Dim ppSlide As Object
On Error Resume Next
Set ppApp = GetObject(, "Powerpoint.Application")
On Error GoTo 0
If ppApp Is Nothing Then
Set ppApp = CreateObject("Powerpoint.Application")
ppApp.Visible = True
ppApp.Presentations.Add
End If
Dim MySheets, i As Long
MySheets = Array(Sheet44, Sheet45, Sheet46, Sheet47, Sheet43, Sheet42, Sheet41, Sheet40, Sheet48) 'these are sheet codenames not sheet name.
MyRanges = Array("A1:Q45", "A1:Q45", "A1:Q45", "A1:Q45", "A1:Q45", "A1:Q45", "A1:Q45", "A1:Q45", "A1:Q45")
For i = LBound(MySheets) To UBound(MySheets)
If ppApp.ActivePresentation.Slides.Count = 0 Then
Set ppSlide = ppApp.ActivePresentation.Slides.Add(1, 12) 'ppLayoutBlank
Else
ppApp.ActivePresentation.Slides.Add ppApp.ActivePresentation.Slides.Count + 1, 12
Set ppSlide = ppApp.ActivePresentation.Slides(ppApp.ActivePresentation.Slides.Count)
End If
Copy_Paste_to_PowerPoint ppApp, ppSlide, MySheets(i), MySheets(i).Range(MyRanges(i)), xl_Bitmap
Next
End Sub
Sub Copy_Paste_to_PowerPoint(ByRef ppApp As Object, ByRef ppSlide As Object, ByVal ObjectSheet As Worksheet, _
ByRef PasteObject As Object, Optional ByVal Paste_Type As PasteFormat)
Dim PasteRange As Boolean
Dim objChart As ChartObject
Dim lngSU As Long
Select Case TypeName(PasteObject)
Case "Range"
If Not TypeName(Selection) = "Range" Then Application.GoTo PasteObject.Cells(1)
PasteRange = True
Case "Chart": Set objChart = PasteObject.Parent
Case "ChartObject": Set objChart = PasteObject
Case Else
MsgBox PasteObject.Name & " is not a valid object to paste. Macro will exit", vbCritical
Exit Sub
End Select
With Application
lngSU = .ScreenUpdating
.ScreenUpdating = 0
End With
ppApp.ActiveWindow.View.GotoSlide ppSlide.SlideNumber
On Error GoTo -1: On Error GoTo 0
DoEvents
If PasteRange Then
If Paste_Type = xl_Bitmap Then
'//Paste Range as Picture
PasteObject.CopyPicture Appearance:=1, Format:=-4147
ppSlide.Shapes.Paste.Select
ElseIf Paste_Type = xl_HTML Then
'//Paste Range as HTML
PasteObject.Copy
ppSlide.Shapes.PasteSpecial(8, link:=1).Select 'ppPasteHTML
ElseIf Paste_Type = xl_Link Then
'//Paste Range as Linked
PasteObject.Copy
ppSlide.Shapes.PasteSpecial(0, link:=1).Select 'ppPasteDefault
End If
Else
If Paste_Type = xl_Link Then
'//Copy & Paste Chart Linked
objChart.Chart.ChartArea.Copy
ppSlide.Shapes.PasteSpecial(link:=True).Select
Else
'//Copy & Paste Chart Not Linked
objChart.Chart.CopyPicture Appearance:=1, Size:=1, Format:=2
ppSlide.Shapes.Paste.Select
End If
End If
'//Center pasted object in the slide
With ppApp.ActiveWindow
If .Height > .Selection.ShapeRange.Height Then
.Selection.ShapeRange.LockAspectRatio = True
.Selection.ShapeRange.Height = .Height * 0.82
End If
If .Selection.ShapeRange.Width > 708 Then
.Selection.ShapeRange.LockAspectRatio = True
.Selection.ShapeRange.Width = 708
End If
.Selection.ShapeRange.Align msoAlignCenters, True
.Selection.ShapeRange.Align msoAlignMiddles, True
End With
With Application
.CutCopyMode = False
.ScreenUpdating = lngSU
End With
'AppActivate ("Microsoft Excel")
End Sub
When you copied that Copy_Paste_to_PowerPoint function you forgot to copy the enum.
Public Enum PasteFormat
xl_Link = 0
xl_HTML = 1
xl_Bitmap = 2
End Enum
Did you get it from somewhere like here? It looks a bit like that version. It looks like you or whoever you got that from stripped out the attribution. You really should put a comment attributing the source of your snippets in there. Not only is it a legal requirement of places like stackoverflow, but it's also quite useful for figuring out what code does, where it came from, and what might be wrong with it.