Problems activating worksheet in excel 2013 - excel

My macro's were working perfect in excel 2010, but in 2013 I have a major problem with activating workbook in vba and than when certain sheet is selected + cell is selected I can fill in data, but when pressing enter or arrow key, the data is set to the first visible page of my file.
This happens when I activate another workbook, but also in the same workbook when I select a certain sheet, the data entered will go to the first sheet... what has changed from excel 2010 to 2013 that makes this happen??
this is the code I use:
Workbooks(MachineInspectieLijst & ".xlsm").Activate
Workbooks(MachineInspectieLijst & ".xlsm").Worksheets(MachineInspectieLijst).Range("V5").Select
When I fill in a value in V5 and enter, the value disappears and shows up on V5 in first page...mostly.
When I manually switch between the pages or workbooks, than it works... I founnd nowhere an answer.
hope somebody has the answer.

Do the process sequentially:
Sub hfjsdfh()
Workbooks(MachineInspectieLijst & ".xlsm").Activate
Worksheets(MachineInspectieLijst).Select
Range("V5").Select
End Sub

This is the actual sub, I tried your suggestion, but exactly the same...Indeed, it is like the second workbook is not really activated, but how to solve? has it to do with the userform who stays loaded? this one must stay loaded, as it contains lot of necessary information and is only unloaded at new start. Nevertheless, I tried to unload as test, but same problem. Can it be due to excel itself?
Private Sub CmdGetInspectionList_Click()
Dim thesentence As String
Dim WB As Workbook
Set WB = ThisWorkbook
Dim WB2 As Workbook
frmKlantSelectie.Hide
Application.EnableEvents = False
If Me.cboDocumentType.Value = "Sales Budget Quotation" Then
MachineInspectieLijst = "Machines_Sales"
WB.Worksheets("PreInspArticles").Range("J1") = "Sales"
Else
MachineInspectieLijst = Me.cboInspectieMachine.Value
End If
loginnaam = StrConv(WindowsUserName, vbUpperCase)
thesentence = "C:\Users\" & loginnaam & "\Dropbox\2_Doc_Service\DATA\Pre_Inspection_Checklist\" & MachineInspectieLijst & ".xlsm"
'checken ofdat de file wel bestaat in de directory
If Dir(thesentence) <> "" Then
MsgBox "Machine Check list exists! Press 'OK' and file will be shown!"
'Test to see if the file is open.
If IsFileOpen(thesentence) Then
Workbooks(MachineInspectieLijst & ".xlsm").Activate
Else
'Display a message stating the file is not in use.
Set WB2 = Workbooks.Open(thesentence)
End If
Else
MsgBox "No machine selected Or Check list not yet existing."
frmKlantSelectie.Show
Me.TxtInspectionList.SetFocus
Exit Sub
End If
WB2.Worksheets(1).Range("V5").Select
Application.EnableEvents = True
End Sub

Related

Updating data in a pivot table workbook from another workbook

I've encountered a strange thing: I've joined three workbooks: Personal Data Tracker, Global Tracker and the workbook with pivots and charts. The logic is as it follows: the user clicks on a button after the work is finished so the data is copied to the GL Tracker. Once the change event is triggered in the GL Tracker Table, the last workbook opens, the pivot is refreshed upon the open vent and the wb is closed.
Everything seems to be working fine, however when I run the macro live, at the very end I get an error message about
"Application-defined or object-defined error".
Only OK and Help button displayed, it doesn't make the VBE Open so I could debug it.
Would anyone know what it may be happening even if the whole chain works fine?
Thank you.
Code from the Personal Tracker:
Sub test()
Dim path As String
Dim wb As Workbook
path = ThisWorkbook.path & "\Dest.xlsm"
Application.ScreenUpdating = False
ThisWorkbook.Sheets("Total").Range("R1").Value = Date
Range("R1").Font.Color = VBA.ColorConstants.vbWhite
Worksheets("TOTAL").Range("B2:B13").Copy
On Error GoTo Handler
Workbooks.Open (path)
On Error GoTo 0
Set wb = Workbooks("Dest")
Worksheets("Sheet1").Range("B2").PasteSpecial Paste:=xlPasteValues
Exit Sub
Handler:
MsgBox "Someone else is saving their data at the moment." & vbNewLine & _
"Please try in a few seconds"
End Sub
Code from the GL Tracker:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim MRange As Range
Dim wbPivot As Workbook
Dim pt As PivotTable
Dim ws As Worksheet
Dim Name As String
Dim answer As VbMsgBoxResult
Set MRange = ThisWorkbook.Sheets(1).Range("Table1")
Name = Application.UserName
Application.ScreenUpdating = False
If Not Intersect(Target, MRange) Is Nothing Then
Application.EnableEvents = True
Set wbPivot = Workbooks.Open("C:\Users\jakub\Desktop\Excel - various\Pivot.xlsm")
End If
'refresh
For Each ws In wbPivot.Worksheets
For Each pt In ws.PivotTables
pt.PivotCache.Refresh
pt.Update
pt.RefreshTable
Next
Next
'saving
Application.ScreenUpdating = True
If Application.UserName <> "Jakub Tracz" Then
MsgBox "User not authorised. Workbook will be closed."
wbPivot.Close True
ThisWorkbook.Close True
Else
answer = MsgBox(Prompt:="Do you want to save and close the workbook?", _
Buttons:=vbYesNo + vbQuestion)
Select Case answer
Case vbYes
wbPivot.Close True
ThisWorkbook.Close True
Case vbNo
MsgBox "Welcome, " & Application.UserName
End Select
End If
End Sub
I'm going to give you a proof of concept code as an example for you to use. This will not exactly answer your question with code you can just copy/paste, but you will be able to use this to put it together the way you want it to work instead of me making assumptions about many things and restructuring it myself.
This simply demonstrates how to use a workbook object variable in one routine that can reference another workbook, and how to make changes to that 2nd workbook and save/close it.
Sub Tracker_Update()
Dim wbPivot as Workbook
' open the workbook
Set wbPivot = Workbooks.Open("C:\Users\jakub\Desktop\Excel - various\Test.xlsx")
' optionally make it hidden
wbPivot.Visible = False
With wbPivot
' pretend this code updates the pivot table
.Worksheets(1).Range("A1") = "hello world"
' Close and save it
.Close True
End With
' optionally clear the variable
' this is not really needed in VBA, but if you eventually
' start using VB.NET with Excel as a COM object,
' you will want to know how to do this part when you are done
Set wbPivot = Nothing
End Sub
I think you will like this approach in the end much better in the end anyway, as the code isn't scattered around so much in different places. Easier to debug later, and easier for someone else to understand what you are doing if and when you leave the company.

Macro Only Finishes If Run Though VBA Application or Macro List

I have a 3 master sheets that I frequently want open (May, June, and July). I have multiple other macros that grab data from these master sheets.
I've created a macro (OpenFiles) that opens them. I want to be able to call OpenFiles at the start of a macro if I know I will be referencing one of these master sheets.
Sub OpenFiles calls another sub(zzGetIt) that checks if the workbook is already open, otherwise it opens it. It works perfectly if I run it from the VBA application, or by choosing it in the macro list in Excel. But if I use a hotkey to call it, or if it is called through another macro, it exits out of all subs after opening a single file (and ends on that workbook instead of activating my original active workbook).
It will open a workbook if one of them is missing, but it will never open more than one (if, say I have only 1/3 workbooks open- 2 should open). And the only scenario where the macro will continue to the msgbox at the end is if all three files are already open.
Please help- I think this must be super obvious since the macro runs fine if I run it from VBA.
I've tried the following:
Removed any error handling that could be hiding a problem with the
sub/function
Set Tools>Options>"Break on all Errors" and I still don't receive any
errors when the sub ends early.
Went through the whole sub with F8- it runs perfectly when I use that.
Call OpenFiles multiple times in a macro but the sub ends after the sub is called the first time so the rest never even run.
Sub zzGetIt(sfullname As String)
Dim ZGetIt As Workbook
Dim wb As Workbook
Dim ReadOnly As Boolean
Dim o As Boolean
Dim sFile As String
sFile = Dir(sfullname)
MsgBox ("Trying to fetch")
For Each wb In Application.Workbooks
If wb.Name = sFile Then
o = True
Exit For
End If
Next wb
If o = False Then
Set zGetIt = Workbooks.Open(sfullname, ReadOnly:=ReadOnly)
End If
'reset o
o = False
MsgBox ("Finished fetching " & sFile)
End Sub
Sub OpenFiles()
Dim Current As Worksheet
Set Current = ActiveSheet
Dim May As String
Dim Jun As String
Dim Jul As String
May = "A:\Files\My Stuff\05 May 2019 - Master.xlsx"
Jun = "A:\Files\My Stuff\06 June 2019 - Master.xlsx"
Jul = "A:\Files\My Stuff\07 July 2019 - Master.xlsx"
Call zzGetIt(May)
Call zzGetIt(Jun)
Call zzGetIt(Jul)
Current.Activate
Set Current = Nothing
Msgbox("I can only get this msgbox if I run from macro list or
VBA application OR if all 3 workbooks were already open before I ran the
macro")
End Sub
If May needs to be opened it will stop at May so I do not receive the msgbox after the sub is called for the first time.
I want the macro to open any of the three workbooks that are not already open and I need it to continue until the msgbox at the very end pops up
I don't see anything obviously wrong with your code that might cause the observed behavior. But I would still do it differently. Perhaps this will help. I've revised your procedures that check for the file already open/open the file if not already open, but apart from that the main difference is that I'm calling this procedure in a loop from OpenFiles.
Option Explicit
Sub OpenFiles()
Dim Current As Worksheet
Set Current = ActiveSheet
Dim files As New Collection
Dim file
files.Add "A:\Files\My Stuff\05 May 2019 - Master.xlsx"
files.Add "A:\Files\My Stuff\06 June 2019 - Master.xlsx"
files.Add "A:\Files\My Stuff\07 July 2019 - Master.xlsx"
For Each file In files
Debug.Print "Fetching file " & file
If isFileOpen(CStr(file)) Then
Debug.Print file & " is already open :) "
Else
Call GetFile(CStr(file), False)
End If
Next
Current.Activate
Set Current = Nothing
MsgBox ("Finished!")
End Sub
Private Function isFileOpen(fullPath$) As Boolean
Dim wb As Workbook
On Error Resume Next
Set wb = Workbooks(Dir(fullPath))
If Err.Number = 0 Then isFileOpen = True
End Function
Private Sub GetFile(fullPath$, readOnly As Boolean)
' No error handling here, this SHOULD raise an error if the file can't
' be opened for any reason (invalid path, locked/in-use unless readOnly=True, etc.
Debug.Print "Attempting to open " & fullPath
Workbooks.Open fullPath, readOnly:=readOnly
End Sub
I've solved the issue... found this article. The issue is using a hotkey with SHIFT. Hotkey used must be lower-case or use a button to call the macro
Ctrl+Shift+a
'won't work
Ctrl+a
'will work

Error Deleting Named Range on Windows 10 Excel 2013 - Older Versions Work Fine

I'm having a problem that I don't really know how to fix. I have a code that runs perfectly in Windows 7 Excel 2010 and always has. In the last few weeks it has developed an error but only when running in Windows 10 Excel 2013.
Basically the below code copies some data sheets to a new workbook in order to strip the VBA out (as this is blocked by company filters). It then loops through all the objects and names and deletes them before sending it via Outlook
Private Sub btnSend_Click()
'---------------------Create the email spreadsheet---------------------------------
Dim FName As String
Dim FPath As String
Dim NewBook As Workbook
Dim EEName As String
Dim nm As Name
EEName = Range("ForeNameCell").Value & " " & Range("SurnameCell").Value
FPath = VBA.Environ("temp") & "\" 'file path to store the copy of the sheet
FName = "NS Form - " & EEName & " " & VBA.Format(VBA.Now(), "mm_dd_yyyy hh mm AMPM")
Set NewBook = Workbooks.Add 'create a new workbook
ThisWorkbook.Sheets("contract Print Out").Copy Before:=NewBook.Sheets(1) 'copy over the printoutallfields sheet
ThisWorkbook.Sheets("Oracle Data").Copy Before:=NewBook.Sheets(1) 'copy over the printoutallfields sheet
'copy and paste special data in new workbook to remove formula
NewBook.Sheets("contract Print Out").Cells.Copy
NewBook.Sheets("contract Print Out").Cells.PasteSpecial xlPasteValues
NewBook.Sheets("Oracle Data").Cells.Copy
NewBook.Sheets("Oracle Data").Cells.PasteSpecial xlPasteValues
'remove back buttons
Dim myshape As Shape
For Each myshape In NewBook.Sheets("contract Print Out").Shapes
myshape.Delete
Next myshape
For Each myshape In NewBook.Sheets("Oracle Data").Shapes
myshape.Delete
Next myshape
'remove links and named ranges
Application.Calculation = xlManual
On Error Resume Next
For Each nm In NewBook.Names
nm.Delete ' This line now errors in W10 E2013
Next
On Error GoTo 0
Application.Calculation = xlCalculationAutomatic
'NewBook.Sheets("PrintOutallFields").Name = "User Data" 'rename it in the destination workbook
Application.DisplayAlerts = False 'turn off overwrite prompt so that it will just overwrite
NewBook.SaveAs Filename:=FPath & FName 'save the file
DoEvents
Application.DisplayAlerts = True 'turn overwrite prompt back on
NewBook.Close
The error that appears is below and when I query the name it is trying to delete it comes up with #NAME?. Every single name seems to appear this way to the code as when I skip ahead and try to go to the next nm, the same thing happens.
I forgot to mention the reason we delete the names from the workbook is due to them always referring the original file. This causes issues when we receive it as the original would of course, always be on the customers PC.
My guess is MS in their eternal wisdom, pushed an update which breaks VBA between versions ... AGAIN! I've had to fix a few of these already but I am stumped by this one.
It seems that my Windows profile had a corruption somewhere. The file also worked on other Windows 10 installations around the office. Re-installing Excel did not fix it, but rebuilding my Windows profile did. This is a first for me, and I thought I had seen everything already.
I would like to thank everyone who looked into this. I'm sure if this were a normal issue with Excel, the enumeration suggestion would have been spot on.

Excel 2016: Active worksheet is not the visible one

I have an Excel macro that creates another workbook for the user to modify. When I try to enter data in a cell in the new workbook, however, I get the error "The cell or chart you're trying to change is on a protected sheet." The sheet in the macro workbook is, in fact, protected, but that sheet is not visible at the time I get the error. When I try to close the visible, newly created workbook, it’s the macro workbook that closes. The last thing my macro does is activate the sheet in the new workbook. What do I have to do to make that work? Having the macro close its own workbook solves the problem, of course, but that’s not what I want to do, since the user needs another macro in the same workbook to process the changes on the new sheet.
The program has over 6000 lines of code (so far), but here is one of the routines that causes the problem.
Private Sub z3_BudgetPrepUpd()
'Build a new workbook initialized to let the user modify data
'for an existing fiscal-quarter budget.
'When this routine executes,
' UserForm1 is still active.
Dim strTracer As String 'error-handling tracer for this subroutine
Dim strFyrQtr As String
On Error GoTo abend
If blnAbort Then Exit Sub
If blnAbortGlobal Then Exit Sub
'Find out which ListBox item the user selected:
If UserForm1.ListBox1.ListCount < 1 Then GoTo aa9000 'ListBox is empty
If UserForm1.ListBox1.ListIndex < 0 Then 'No item selected
strMsgTitle = udtPrm.msgTtl
strMsgPrompt = "Please select a fiscal quarter to update."
Call z0_MsgBox
GoTo aa9000
End If
strFyrQtr = UserForm1.ListBox1.Value 'Selected item in ListBox
'Close UserForm1:
UserForm1.Hide
ThisWorkbook.Sheets(c_WKS_WELCOME).Activate
'Build the udtBgt() array with data for the specified quarter:
lngBgtHiNdx = -1
Call zz_GetBudgetForQtr(strFyrQtr)
If blnAbort Then GoTo aa9000
'Build a new workbook for the user to update budget amounts:
Workbooks.Add
Set wkbNewBook = ActiveWorkbook
'Save the names of the default worksheets
'so we can delete them later:
strDfltSheets() = z0_SheetNames(wkbNewBook)
'Build a worksheet with data from the udtBgt() array:
Call z3_BuildBudgetUpdSheet
If blnAbort Then GoTo aa9000
'Delete the default worksheets:
Call z0_DeleteSheets(wkbNewBook, strDfltSheets())
If blnAbort Then GoTo aa9000
wkbNewBook.Sheets(c_WKS_IPT_BUDGET).Activate
'Excel 2016 Bug:
'We need to close ThisWorkbook to allow the user
'to work with the book we just created:
Application.DisplayAlerts = False
ThisWorkbook.Close
aa9000:
Exit Sub
abend:
lngErr = Err.Number
strErr = Err.Description
blnAbort = True
Application.Cursor = xlDefault 'no more hourglass
strMsgTitle = "Program Error"
strMsgPrompt = "The following error occurred:" & Chr(10) & Chr(10) & _
"Error No. " & CStr(lngErr) & Chr(10) & _
"Error Description: " & strErr & Chr(10) & _
"Subroutine: z3_BudgetPrepUpd" & Chr(10) & _
"Tracer: " & strTracer
Call z0_MsgBox
Resume aa9000
End Sub
You use ThisWorkbook which I agree with. You use ActiveWorkbook which I hardly ever use.
I'd recommend using a variable to store reference to workbooks other than that which houses your code. So use
Dim wb As Excel.Workbook
Set wb = Application.Workbooks.Open("c:\test.xlsm") 'for opening
'* or
Set wb = Application.Workbooks.Add 'for creating a new one
'* or
Set wb = Application.Workbooks.Item("AlreadyOpen.xlsm") 'for referencing one already open
'* from hereon use wb instead of ActiveWorkbook
wb.Worksheets.Item(1).Visible = True
Thanks, everyone, for your interest and suggestions. I have solved the problem by redesigning the application without UserForms or external workbooks. Office 2016 has many issues, and perhaps this is one of them. In any case, I have no more time to research it.

Worksheet copy to include copy of Sheet Buttons

I have a workbook where I have a worksheet that is copied by the user hitting a button (runs the code below). I want to make a copy of the worksheet as a new instance (this part is working) and also include the buttons on the copied sheet (this is where I am having trouble in later versions of excel).
The code works in older versions of excel but in 2010 and above the worksheet is copied but the buttons are not.
My current code is as follows;
Private Sub NewOrderSheet()
Application.ScreenUpdating = False
Dim pN As String
Dim pNB As String
Dim pNC As String
Dim pND As String
pN = Worksheets("ProjectDetails").Range("B5").Text
pND = ("Order Number: " & pN)
pNB = InputBox(pND)
If Len(pNB) = 0 Then
MsgBox "An order number must be given to be able to generate a new order.", vbCritical
Exit Sub
Else
End If
pNC = pN & "-" & pNB
Worksheets("QuoteSheet").Copy After:=Worksheets(Worksheets.Count)
Worksheets(Worksheets.Count).name = pNC
Application.ScreenUpdating = True
End Sub
Basically I create a new instance of the worksheet and then allow the user to give the worksheet a new name (in this case a new order).
The worksheet contains 2 buttons;
Button 1 - Copies the worksheet into a new workbook and removes all formulas
Button 2 - Formats the used range for printing
I have searched the questions and tried a number of variations but cannot seem to get the buttons to copy over.
I am very new to VB for excel so my apologies in advance if this is something simple.
I had the same problem. I checked all security concerning settings and tried everything. And then I found out that deleting the %Temp% Folder helps.
The true reason is, you have to search for a "MSForms.exd" File and delete it.
Then everything works fine again (:

Resources