Excel VBA, Code name appearing with sheet name - vba

Why is that when I have the following VBA code:
public sub Run
End Sub
Sometimes it appears as Run in the macro list on the view tab but sometimes it appears as sheet1!Run?

You've put the macro into one of the worksheet code sheets. This probably occurred by opening the VBE with a right-click to the worksheet name tab and choosing View Code.
The macro can reside there but it will remain Private to that worksheet unless specifically declared otherwise. Generally, a module sheet is the preferred location.
It's also a bad idea to name your macros with reserved words. Run is a function as in Application.Run and your macro can only cause confusion if it carries the same name.

Related

Find worksheet name mapping in Excel

I have inherited an Excel workbook with several worksheets, all with named tabs. I have some VBA code that runs depending on buttons and inputs. When I compare the VBAProject and the list of Excel Objects, the sheet's names match the tabs. All good so far.
However, within the VBA code and on the spreadsheets itself, it refers to other worksheets. They are still part of the workbook, and I think that the code was created, and then tabs were renamed. But I don't know how Excel keeps the connection, or, more importantly, how I am supposed to figure out the connections.
So, for instance, I have a VLOOKUP that refers to MiscDataRange
=IF((VLOOKUP(E4,MiscDataRange,4,0))="Y"...
I don't know what MiscDataRange is, but within the VBA code I find one reference. Right after specifying worksheet "Misc Interrupt", which is NOT any of the named tabs.
Worksheets("Misc Interrupt").Range("H2:H47") = "N" 'Reset to N at noon.
UpdateData
Range("MiscDataRange").ClearContents
I do have a sheet called MiscInt, and it appears to be the sheet that "Misc Interrupt" is using and MiscDataRange is referencing.
My problem is there is a hole in my knowledge - I can guess that MiscInt and Misc Interrupt are the same worksheet, that the VLookup is referring to data on the MiscInt sheet. But I am reduced to guessing. I cannot find anything in the file that maps those two as the same. Where would I look to find that?
This question seems related, except he simply has a VLookup, and isn't looking at the VBA code: Non-existent Excel Worksheet, but Formulas and Defined names still work?. In addition, from the VBA code, I can see hidden and visible worksheets.
You can open the Names manager by going to the Formula Tab and clicking Names Manager or pressing ctrl+F3 or you can paste a list of Names and what the names reference by pressing F3. It may be necessary to unhide the names first.
Sub ShowAllNames()
Dim n As Name
For Each n In ThisWorkbook.Names
n.Visible = True
Next
End Sub
If I understand your question, you're looking to find where those named ranges are.
You can use a sub like this:
Sub t()
Debug.Print "Sheet: " & Range("testNamedRange").Parent.Name
Debug.Print "Full Location: " & Range("testnamedrange").Name
Debug.Print "File path: " & Range("testnamedrange").Worksheet.Parent.Path
End Sub
Does that help?

Referencing the selection in deactivated Workbook

Private Sub Workbook_Deactivate()
ThisWorkbook.ActiveSheet.Selection.Copy
End Sub
I'd like to copy the selection in the deactivated workbook. But this doesn't work, indeed, I got a run-time error.
Damn! It is possible!
Private Sub Workbook_Deactivate()
ThisWorkbook.Windows(1).Selection.Copy
End Sub
Explanation:
Both ActiveSheet and Selection are children objects of the Application object, not the Workshet or Workbook objects. (See MSDN: Selection and ActiveSheet.) Selection means the currently selected item in the active window. Same for ActiveSheet.
Now it turns out that you can specify a window object for both of them. Normally every Workbook has one window, but you can create multiple windows for each open workbook. Anyhow, every open workbook that you can click and select will have at least one window. This is whateverworkbook.Windows(1).
ThisWorkbook always references the workbook running the macro (that means the workbook actually containing the VBA code). In your case, that is the one you are leaving. (Unless you want the macro to run from any workbook you are deactivating, in which case you'd have to come up with a custom event handler that catches each workbook deactivate event...)
And that's it, really. You can reference a selection in another workbook, you just have to attack it through it's Window.
Thanks for the good question, I have learned something very valuable today. :)

More than one workbook object in project explorer

I have this strange problem. I have a vba project, where the project explorer displays more than one workbook object. It is exactly the same as in this SO question, but I don't have any faulty references to uncheck.
However, I do know what's caused it and I'm sure you can all duplicate. What I did was use the codename for a sheet as a byref argument for a simple sub and at the end of the sub, nulled the worksheet object. So I nulled the whole sheet through the reference.
Something like:
Option Explicit
Sub test_1()
test_2 sh:=Sheet2
End Sub
Sub test_2(ByRef sh As Worksheet)
Set sh = Nothing
End Sub
If you run test_1, it will run without problems. But after that, the 'Sheet2' codename is invalid. And if you close and reopen the workbook, you'll see what I mean. Excel creates a new worksheet with the same name (but another CodeName). Any data stored in the cells of the sheet is not lost. The old CodeName references the Workbook Object.
I have not found a way to restore or remove the old references so far (other then move all the objects to a new workbook). I am using Excel 2013.
Solution is of course not so null the worksheet, but does anyone have any idea how to restore?
Well, after suffering this weird behaviour of Excel I can finally say that I have tried man times and that I can confirm that the cause (at least for my experiments) was indeed using User Defined Functions (UDFs). There is no way of fixing a Workbook once the extrange sheets appear. My approach was to just create a new Workbook and copy all the Modules and all the sheets from the old (broken) one.
Just make sure to not use user defined functions if you are having this issue.

VBA Select a sheet when the workbook is opened

The following program doesn't work when I open my workbook. What are the possible reasons?
' Select the first sheet when the workbook is opened.
Private Sub Workbook_Open()
Sheet4.Select
Sheet4.Range("B1").Select
End Sub
If you hit alt+F11 to go to the VBA code editor. On the left side, under the file name you will see the different sheets, and whatever modules you might have in there. If you go under the ThisWorkbook module
and place your code there, it will automatically run when you start up the Excel File.
you are using the "Select" Method without an Activating a Sheet First!
Yes, when you have closed your workbook last time, the current sheet will remain in the memory index and when you will again open the same workbook, the pointer search for the most recent sheet used based on the index no.
'Here is the code
Private Sub Workbook_Open()
Sheet4.Activate
Sheet4.Select
Sheet4.Range("B1").Select
End Sub
using "Select Method" without Activating the Parent Object is a Crime. lol
Hope this will help you.

Where Exactly To Store VBA

We receive Excel files daily from our field offices which I have to clean and re-format (about 110 columns and 500 rows-worth) using VBA.
I need to save my VBA as a macro so we can use it to clean up all the workbook we receive by running the macro and saving the edited sheet as a new worksheet by getting the name from UserForm Combobox items.
Where exactly should I store the VBA snippets? I mean when I open the Visual Basic panel, I have these three options:
Running The Code From Microsoft Excel Object :Sheets1(Sheet1)
Running the Code From An Inserted Module
Running the Code From User Form
If I am supposed to use options 1 or 2, how can I call the UserForm for saving the sheet?
I Recomend you to use modules (Option B)
Option C goes with option B, ill explain, you can create a sub in a module in option B, then you can do:
UserForm1.show
In Option B I would writte this code, but before trying this i recomend you to understand a bit more of vba
sub ClearWBs()
'opening workbook
Workbooks.Open Filename:="c:\book1.xls"
'your code
'your code
'below code for saving and closing the workbook
Workbooks("book1.xls").Activate
ActiveWorkbook.Save
ActiveWorkbook.Close
end sub
Use Module:
If your VBA code focusses on data summarization and manipulation I suggest you use a Module.(example is what you have described in your question).
Use Form:
If what you wan't to do requires a GUI(Graphical User Interface) then you'll have to resort to Form where you can design your GUI. (example is if you have many fields that the user needs to fill-up with distinct values in which you provide the choices)
Use Excel Object:
If what you wan't to do has something to do with events happening on Worksheet and/or Workbook, like for example whenever you add sheet the macro runs, or when you open or close the workbook the macro runs then you will have to write the macro in the Excel Object.
This is basically what i have in mind, hope this helps.
If you receive files that do not contain VBA and you need to apply the same code on those files all the time then I propose that you either save that code in your personal workbook.
You can see how to do that here: http://office.microsoft.com/en-ca/excel-help/copy-your-macros-to-a-personal-macro-workbook-HA102174076.aspx
This is nice because you can also tie it to keyboard shortcut or just have it always ready for you to use.
The disadvantage is that it will only be set up per user session per computer. What you can do is have that code all set up in a module and then import it into your personal workbook if you change session or if someone else has to do it.
Once it's done, you will not have to include the module in your files your receive again.