Why doesn't this simple VBA code work in Excel? - excel

I'm quite new to programming with VBA (or any language, let's be honest). I'm trying to do a project for work, adding short sections at a time to see if the code still works, and trying out new code in a separate Sub. I've come across an error that I can't get around. The results don't change when they're the only line in a separate Sub.
The following code works:
ActiveWorkbook.Sheets("Template").Copy After:=ActiveWorkbook.Sheets("Student info")
Whereas the following code, when run, breaks with a 424 run-time error (object required). I've tried selecting instead of naming, still no luck. It does successfully copy the worksheet to the correct place, despite the error, but is called 'Template (2)'.
ActiveWorkbook.Sheets("Template").Copy(After:=ActiveWorkbook.Sheets("Student info")).name = "newname"
This is very confusing because the code below does work. Is it just that trying to name something after using 'add' does work, but after 'copy', it doesn't?
ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.Sheets("Student info")).name = Student_name
Thanks in advance for any help.

The reference (to the created copy) as return value (of a function) would be useful, but as Worksheet.Copy is a method of one worksheet (in opposite to Worksheets.Add what is a method of the worksheets-collection), they didn't created it. But as you know where you created it (before or after the worksheet you specified in arguments, if you did), you can get its reference by that position (before or after).
In a function returning the reference:
Public Enum WorkdheetInsertPosition
InsertAfter
InsertBefore
End Enum
Public Function CopyAndRenameWorksheet(ByRef sourceWs As Worksheet, ByRef targetPosWs As Worksheet, ByVal insertPos As WorkdheetInsertPosition, ByVal NewName As String) As Worksheet
'If isWsNameInUse(NewName) then 'Function isWsNameInUse needs to be created to check name!
'Debug.Print NewName & " alredy in use"
'Exit Function
'End If
With sourceWs
Dim n As Long
Select Case insertPos
Case InsertAfter
.Copy After:=targetPosWs
n = 1
Case InsertBefore
.Copy Before:=targetPosWs
n = -1
Case Else
'should not happen unless enum is extended
End Select
End With
Dim NewWorksheet As Worksheet
Set NewWorksheet = targetPosWs.Parent.Worksheets(targetPosWs.Index + n) 'Worksheet.Parent returns the Workbook reference to targetPosWs
NewWorksheet.Name = NewName ' if name already in use an error occurs, should be tested before
Set CopyWorksheetAndRename = NewWorksheet
End Function
usage (insert after):
Private Sub testCopyWorkSheet()
Debug.Print CopyAndRenameWorksheet(ActiveWorkbook.Sheets("Template"), ActiveWorkbook.Sheets("Student info"), InsertAfter, Student_name).Name
End Sub
to insert the copy before the target worksheet, change third argument to InsertBefore (enumeration of options).
New Worksheet.Name needs to be unique or you'll get an error (as long you not implemented the isWsNameInUse function to check that).
Also note that there is a difference between .Sheets and .Worksheets
You can get the links to the documentation by moving the cursor (with mouse left-click) in the code over the object/method you want more infos on and then press F1

Related

Function vs Sub(ByRef)

About
This question is not about when to use a Function or a Sub, or the difference between ByRef and ByVal (although some insights will be unavoidable).
It is about scenarios which are 'commonly' solved with a Function, but can optionally be solved with a Sub using ByRef in the sense of 'modifying'.
The Code
Consider the following function:
' Returns the worksheet (object) with a specified name in a specified workbook (object).
Function getWsF(wb As Workbook, _
ByVal wsName As String) _
As Worksheet
' 'getWsF' is 'Nothing' by default.
' Try to define worksheet.
On Error Resume Next
Set getWsF = wb.Worksheets(wsName)
End Function
You can utilize it like the following:
' Writes the name of a specified worksheet, if it exists, to the `Immediate` window...
Sub testFunction()
Const wsName As String = "Sheet1"
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
' Define worksheet.
Dim ws As Worksheet
Set ws = getWsF(wb, wsName)
' Test if worksheet exists.
If Not ws Is Nothing Then
Debug.Print "The worksheet name is '" & ws.Name & "'."
Else
Debug.Print "Worksheet '" & wsName & "' doesn't exist in workbook '" _
& wb.Name & "'."
End If
End Sub
But you can also write each of the procedures in the following way:
' Although 'ByRef' is not necessary, I'm using it to indicate that whatever
' its variable is referring to in another procedure (in this case
' a worksheet object), is going to be modified (possibly written to
' for other datatypes).
Sub getWsS(ByRef Sheet As Worksheet, _
wb As Workbook, _
ByVal wsName As String)
' 'Sheet' could be 'Nothing' or an existing worksheet. You could omit
' the following line if you plan to use the procedure immediately
' after declaring the worksheet object, but I would consider it
' as too risky. Therefore:
' 'Reinitialize' worksheet variable.
Set Sheet = Nothing
' Try to define worksheet.
On Error Resume Next
Set Sheet = wb.Worksheets(wsName)
End Sub
' Writes the name of a specified worksheet, if it exists, to the `Immediate` window...
Sub testSub()
Const wsName As String = "Sheet1"
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
' Define worksheet.
Dim ws As Worksheet
getWsS ws, wb, wsName
' Test if worksheet exists.
If Not ws Is Nothing Then
Debug.Print "The worksheet name is '" & ws.Name & "'."
Else
Debug.Print "Worksheet '" & wsName & "' doesn't exist in workbook '" _
& wb.Name & "'."
End If
End Sub
Side by Side
Procedure
Function getWsF(wb As Workbook, _ Sub getWsS(ByRef Sheet As Worksheet, _
wsName As String) _ wb As Workbook, _
As Worksheet wsName As String)
Set Sheet = Nothing
On Error Resume Next On Error Resume Next
Set getWsF = wb.Worksheets(wsName) Set Sheet = wb.Worksheets(wsName)
End Function End Sub
Usage (relevant)
' Define worksheet. ' Define worksheet.
Dim ws As Worksheet Dim ws As Worksheet
Set ws = getWsF(wb, wsName) getWsS ws, wb, wsName
The Question(s)
Is the second solution viable?
I'm looking for a proper description of what each of the relevant two procedures do and some insights
in terms of common practice, readability, efficiency, pitfalls ...
In your case, I would use the Function approach and here are a few reasons:
I can use the result of the Function without storing the returning variable:
With getWsF(ThisWorkbook, "Sheet1")
'...
End With
Obviously, I would need to be sure it never returns Nothing or have some error handling in place.
or
DoSomething getWsF(ThisWorkbook, "Sheet1")
where DoSomething is a method expecting a Worksheet/Nothing
As #TimWilliams mentioned in the comments, if you don't expect multiple return values then this is the "expected" way to do it. A well-established convention is that if the method has no return value it should be a Sub. If it has a single return value then it should be a Function. If it returns multiple values then it should also be a Function and:
you either use a Class or Type to pack them as one result
or, the Function returns a primary value as the result and the rest of the return values ByRef (see #UnhandledException's answer for an example).
If you ever need to call the method with Application.Run then Function is safe. Using a Sub often leads to Automation Errors or code simply stops running after the method is executed. It doesn't matter if you need to use the result of the Function or not, don't call a Sub with Application.Run if you don't want nasty errors. Of course, to avoid issues with Application.Run, you could have a Function that doesn't get assigned a return value and still return the Worksheet ByRef but this would be too confusing for the reader.
Edit #1
Forgot to mention that the Application.Run automation errors are happening when calling methods from a different document (for Excel - different Workbook)
Edit #2
In this section I will try to address the proper description side of your question, without doing a begginer and an advanced explanation but a combined one.
Difference between a Sub and a Function
A Sub is just a function that does not return a value after the function executes. In lots of languages, such a function is called a Void Function.
The implications is that a Sub is just a stand-alone statement. It cannot be called from inside an expression. You can only call it with one of:
MySub [argsList]
Call MySub([argsList])
On the other hand, a Function can be used inside statements like:
arguments to other methods e.g. DoSomething MyFunction(...); Debug.Print MyFunction(...)
assignment e.g. x = MyFunction(...)
With blocks e.g. With MyFunction(...)
method chaining e.g. MyFunction(...).DoSomething
The convention mentioned above:
A well-established convention is that if the method has no return value it should be a Sub. If it has a single return value then it should be a Function
becomes quite clear when we understand that a Sub does something and a Function returns a single value, by definition.
Similarity between a Sub and a Function
Both value-returning functions (Function in VBA) and void functions (Sub in VBA) are receiving values as parameters. In VBA, it is possible to return results via ByRef parameters. Not all languages support ByRef parameters (e.g. Java - except modifying members of Objects for example).
Note that porting code from a platform that supports ByRef to another one that does not, can be quite time-consuming if the ByRef approach is abused in the source platform.
Difference between ByVal and ByRef parameters
Passing by value (ByVal):
a new memory space is allocated for a new variable which will be of local scope to the method being called
the contents of the original variable are copied in the newly allocated space of the new variable (for Objects the address of the interface Virtual Table is copied instead)
contents of the original variable are NOT changed regardless of what the method does
it is much safer because the programer does not need to keep in mind/care about other parts of the program (specifically the calling method)
Passing by reference (ByRef):
a new variable is created but no new memory space is allocated. Instead the new variable points to the memory space occupied by the original variable being passed from the calling method. Note that for Objects, the original variable is passed entirely (no new variable is created) unless the interface is different (passing a Collection as an Object type parameter - Object stands for IDispatch) but this is a discussion outside of the scope of this answer. Also note that if the parameter is declared as Variant, there are more complex operations happening to facilitate the redirection
the contents of the original variable can now be changed remotely because both the original variable and the newly created one point to the same memory space
it is considered more efficient because no new memory is allocated but this comes with the downside of increasing complexity
Comparison of the presented methods
Now that we have some understanding of the differences, we can look at both the presented methods. Let's start with the Sub:
Sub getWsS(ByRef Sheet As Worksheet, wb As Workbook, ByVal wsName As String)
Set Sheet = Nothing
On Error Resume Next
Set Sheet = wb.Worksheets(wsName)
End Sub
First of all, there should be an On Error GoTo 0 statement before the End Sub because otherwise the Error 9 is propagated up the calling chain (if sheet not found) and can affect logic inside other methods, long after the getWsS method has returned.
The method name starts with the verb "get" which implies that this method returns something but the method declaration is a Sub which is, by definition, more like a Do Something than a Return Something. Readability is certainly affected.
There is a need for an extra ByRef parameter to return the single piece of result. Implications:
it affects readability
it requires a declared variable inside the calling method
the result cannot he chained/used in other expressions within the calling method
it requries the extra line Set Sheet = Nothing to make sure the original variable does not retain previous contents
Now, let's look at the Function approach:
Function getWsF(wb As Workbook, ByVal wsName As String) As Worksheet
On Error Resume Next
Set getWsF = wb.Worksheets(wsName)
End Function
Same as before, there should be an On Error GoTo 0 statement before the End Function because otherwise the Error 9 is propagated up the calling chain. Also, the Workbook can be passed ByVal as best practice.
Obvious differences:
the name getSomething is perfect for a function that returns Something. Readability is far better than the Sub couterpart
the reader/maintainer of the code instantly knows that the function returns a Worksheet just by looking at the return type (as opposed to looking through a list of ByRef parameters and figuring out which one is the return variable)
the result can be chained/used in expressions
no extra lines of code are needed, the default returning value is already Nothing
the most widely accepted convention is used
I've used CTimer and it seems like on my x64 machine, the Sub approach runs faster with about 20ms when running the methods for a million times. Are these minor efficiency gains worth the loss in readability and flexibility of use? That is something that only the maintainer of the code base can decide.
To answer your question directly:
Q: Is it viable?
A: Yes, it will compile and carry out the functionality that you're expecting.
The grey area comes about when you ask should you do this.
There's definitely nothing stopping you (assuming you aren't subject to some company coding standards or anything). Typically however, functions are used to take in parameters, perform some kind of logic and return a value or object at the end of that logic.
Functions are typically non-destructive and don't change the values or properties of the input parameters. This becomes especially important for code readability and maintenance because other developers (and even yourself a few months from now) will read the code expecting functions to behave in a certain way.
Sub routines on the other hand are not expected to return anything, and so they are used to run concise, related sections of code that carry out some kind of logic relevant to the application. Going back to the point of readability and maintenance, it's reasonable to assume that objects and properties will change inside of a sub routine and so again this makes the developer's life a little easier.
Ultimately there's no hard and fast rules - but there are years of experience and best practice which are often good advice to take on in these scenarios :)
A good example for using both, a function and a ByRef parameter is a 'Try' function:
Public Function TryGetMyValue(ByRef outMyValue As Long) As Boolean
On Error Goto Catch
outMyValue = GetMyValue() 'Does anything to retrieve the value and could raise an error...
TryGetMyValue = True
Done:
Exit Function
Catch:
Resume Done
End Function
It could be used like that:
Public Sub TestTryGetMyValue()
Dim myValue As Long
If Not TryGetMyValue(myValue) Then Exit Sub
Debug.? "MyValue is: " & myValue
End Sub

How to Use the Find Function

I have recently Written some code to take an input from a userform text box and search for it in my database. If found I would like it to return the value and insert it into cell A1149; I have written the below code but it gives me error #424 "Object Required". I am very new to VBA so any and all help is greatly appreciated.
Private Sub CMDSearch_Click()
Dim pesquisa As Range
Set pesquisa = Worksheets("Petrobras").Activate.Range("$W:$W") _
.Find(What:=Opp_Num_Search.Value, LookIn:=xlValues, Lookat:=xlWhole).Activate
Worksheets("Petrobras").Range(A1149).Value = pesquisa.Value
UserForm1.Hide
End Sub
Range.Activate doesn't return anything, it's like a Sub procedure:
Public Sub DoSomething()
' does something...
End Sub
If you did Set foo = DoSomething.Something, you'd get the same error: an object is required, otherwise that .Something member call is illegal (except now the error would be at compile-time and not run-time, because of how binding works).
Set pesquisa = Worksheets("Petrobras").Activate...
You don't want to Activate any sheets.
Part of the problem is the implicit late-binding going on: Worksheets returns an Object, so everything you wrote after that, all these chained member calls, can only be resolved at run-time.
Make it early-bound, by declaring an explicit Worksheet variable:
Dim sheet As Worksheet
Set sheet = Worksheets("Petrobras")
Now if you want to activate it, you can do sheet.Activate (but you don't need to). And if you want to get a Range from that worksheet, you can make a .Range member call, and the IDE will now help you do it:
Dim result As Range
Set result = sheet.Range("$W:$W").Find(...)
NEVER chain any member calls to what Range.Find returns. If the search turned up a result, you have a Range object. If it didn't, you have Nothing - and any member call made against Nothing will always raise run-time error 91.
Validate the search result first:
If result Is Nothing Then
MsgBox "Could not find '" & Opp_Num_Search.Value & "' in column W."
Exit Sub
End If
Or:
If Not result Is Nothing Then
sheet.Range("A1149").Value = result.Value
End If
Note that A1149 is a string literal representing a cell address, and as such it must be surrounded with double quotes ("). If it's not in double quotes and it looks like a valid variable name, VBA will treat it as ..a variable... and that will cause yet another error (1004), because Range will be rather unhappy to work with a Variant/Empty value.
To prevent VBA from "declaring" on-the-fly variables with a typo (and causing hard-to-find bugs), make sure you have Option Explicit at the very top of every module in your project.
One last thing:
UserForm1.Hide
This hides the default instance of UserForm1, which may or may not be the current object / instance that's shown - and the form itself has no way to know how it was shown:
UserForm1.Show '<~ shows the default instance
With New UserForm1
.Show '<~ shows a new (non-default) instance
End With
For this reason, you should avoid referring to the default instance in a form's code-behind. Use Me instead:
Me.Hide
That way you're referring to whatever instance of the form is currently shown, whether that's the default instance or not. See UserForm1.Show for more information, tips, pitfalls and common mistakes involving userforms.
Note that Rubberduck has quite a few inspections that can identify and warn you about (and often, automatically fix) most of these problems. Rubberduck is a free and open-source VBIDE add-in project I manage.

How to add Worksheets, after last active sheet, with InputBox?

How can I implement "count" from the InputBox?
I encountered a syntax error with the below code.
Sub AddSheets_via_Input_Box()
Dim Prompt As String
Dim Caption As String
Dim DefValue As Long
Dim NumSheets As String
DefValue = 1
Prompt = "...how many people are working Fraud Today?"
Caption = "Tell me…"
NumSheets = InputBox(Prompt, Caption, DefValue)
Sheets.Add(After:=Temp,Count:=NumSheets)
End Sub
Problem starts at:
(After:=Temp,Count:=NumSheets)
It all works with :
Sheets.Add Count:=NumSheets
I need those new sheets added after two exiting sheets in that workbook.
As far as I can see you haven't declared Temp in your code (if it's a sheet's code name then you need to let us know that also).
Also you can't use parentheses like that in VBA, you only use them when you're grouping something, or evaluating something to return to the left hand side of an expression.
here's a tidied up version:
Sub AddSheets_via_Input_Box()
Dim numberOfSheets As Integer
'// Here we use parentheses because we are returning a value to numberOfSheets...
numberOfSheets = CInt(Trim$(InputBox("...how many people are working Fraud Today?", "Tell me…", 1)))
If IsNumeric(numberOfSheets) Then
With ActiveWorkbook
'// Here we DON'T use parentheses because we aren't returning or evaluating anything...
.Sheets.Add After:=.Sheets("Temp"), Count:= numberOfSheets
End With
Else
MsgBox "Invalid parameter supplied - use numbers only"
End If
End Sub

Forumula to create Table of Content in Excel

I am looking for a formula which can directly be used in cells to read all the active tabs' name. Please refer the screen shot for the same.
There is also a =MID(CELL("filename"),FIND("]",CELL("filename"))+1,255) formula, but it is only giving the current tab name.
Though this is easily possible using macro, but would be great if can get formula for that.
There is a way to do this through formula's only,
Have a look here
It feels a bit double to post exactly how it's done, but the approach makes use of a named range and a lookup formula
It's fairly easy to do
I note you say formula but you could use a very simple User Defined Function (UDF) which goes in a standard module in the VBE (which you open with Alt+F11)
Option Explicit
Public Function GetTabName(ByVal tabIndex As Long) As String
GetTabName = ThisWorkbook.Worksheets(tabIndex).Name
End Function
The sheet index gets passed into the UDF as a parameter and the associated sheetname is returned.
If testing for visible sheet you could use the following, which has additional handling for sheet not found:
Option Explicit
Public Function GetTabName(ByVal tabIndex As Long) As String
Dim ws As Worksheet
On Error GoTo Errhand
Set ws = ThisWorkbook.Worksheets(tabIndex)
If ws.Visible Then
GetTabName = ThisWorkbook.Worksheets(tabIndex).Name
Else
GetTabName = "N/A"
End If
Errhand:
If Err.Number <> 0 Then
Select Case Err.Number
Case 9
GetTabName = "Sheet not found"
End Select
End If
End Function
UDF Limitations

Modifying a spreadsheet using a VB macro

I have two spreadsheets... when one gets modified in a certain way I want to have a macro run that modifies the second in an appropriate manner. I've already isolated the event I need to act on (the modification of any cell in a particular column), I just can't seem to find any concrete information on accessing and modifying another spreadsheet (this spreadsheet is located on a different LAN share also... the user has access to both, though).
Any help would be great. References on how to do this or something similar are just as good as concrete code samples.
In Excel, you would likely just write code to open the other worksheet, modify it and then save the data.
See this tutorial for more info.
I'll have to edit my VBA later, so pretend this is pseudocode, but it should look something like:
Dim xl: Set xl = CreateObject("Excel.Application")
xl.Open "\\the\share\file.xls"
Dim ws: Set ws = xl.Worksheets(1)
ws.Cells(0,1).Value = "New Value"
ws.Save
xl.Quit constSilent
You can open a spreadsheet in a single line:
Workbooks.Open FileName:="\\the\share\file.xls"
and refer to it as the active workbook:
Range("A1").value = "New value"
After playing with this for a while, I found the Michael's pseudo-code was the closest, but here's how I did it:
Dim xl As Excel.Application
Set xl = CreateObject("Excel.Application")
xl.Workbooks.Open "\\owghome1\bennejm$\testing.xls"
xl.Sheets("Sheet1").Select
Then, manipulate the sheet... maybe like this:
xl.Cells(x, y).Value = "Some text"
When you're done, use these lines to finish up:
xl.Workbooks.Close
xl.Quit
If changes were made, the user will be prompted to save the file before it's closed. There might be a way to save automatically, but this way is actually better so I'm leaving it like it is.
Thanks for all the help!
Copy the following in your ThisWorkbook object to watch for specific changes. In this case when you increase a numeric value to another numeric value.
NB: you will have to replace Workbook-SheetChange and Workbook-SheetSelectionChange with an underscore. Ex: Workbook_SheetChange and Workbook_SheetSelectionChange the underscore gets escaped in Markdown code.
Option Explicit
Dim varPreviousValue As Variant ' required for IsThisMyChange() . This should be made more unique since it's in the global space.
Private Sub Workbook-SheetChange(ByVal Sh As Object, ByVal Target As Range)
' required for IsThisMyChange()
IsThisMyChange Sh, Target
End Sub
Private Sub Workbook-SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
' This implements and awful way of accessing the previous value via a global.
' not pretty but required for IsThisMyChange()
varPreviousValue = Target.Cells(1, 1).Value ' NB: This is used so that if a Merged set of cells if referenced only the first cell is used
End Sub
Private Sub IsThisMyChange(Sh As Object, Target As Range)
Dim isMyChange As Boolean
Dim dblValue As Double
Dim dblPreviousValue As Double
isMyChange = False
' Simple catch all. If either number cant be expressed as doubles, then exit.
On Error GoTo ErrorHandler
dblValue = CDbl(Target.Value)
dblPreviousValue = CDbl(varPreviousValue)
On Error GoTo 0 ' This turns off "On Error" statements in VBA.
If dblValue > dblPreviousValue Then
isMyChange = True
End If
If isMyChange Then
MsgBox ("You've increased the value of " & Target.Address)
End If
' end of normal execution
Exit Sub
ErrorHandler:
' Do nothing much.
Exit Sub
End Sub
If you are wishing to change another workbook based on this, i'd think about checking to see if the workbook is already open first... or even better design a solution that can batch up all your changes and do them at once. Continuously changing another spreadsheet based on you listening to this one could be painful.

Resources