Accessing Excel sheet without mentioning its name in VBA program - vba

How can I refer Excel sheet using VBA which has only one sheet without mentioning the sheet name in my program? Actually the sheet name might change next time with new data and it is creating a problem in my automation process.

If your macro is running on the same file, you can simply refer to it using the global ActiveWorksheet object.
If you are loading it from somewhere else, you will be probably doing something like this:
Dim objWorkbook as Workbook
Dim objWorksheet as Worksheet
Set objWorkbook = Workbooks.Open("my-file.xlsx")
Set objWorksheet = objWorkbook.Worksheets(1)

To add something to #Mr.E. answer, note that each sheet as 2 names:
- the tab name, visible by the users, appearing within parenthesis in the Project Explorer
- the vba sheet name, appearing first in Project Explorer
So Sheets("MyList").Range(myRange) could be the exact equivalent of
Sheet1.Range(myRange) and, of course to Worksheets(1).Range(myRange) if you have only 1 sheet.

Related

Excel keeps crashing when I set a certain worksheet

The workbook keeps crashing when it gets to the
Set wsEDF = Worksheets("edf master") line. I have tried to delete the sheet and then reinstate it and the same thing happens. Am a bit confused.
Sub CopyGroups()
Application.ScreenUpdating = False
Set wsMarex = Worksheets("marex master")
Set wsMQ = Worksheets("macquarie master")
Set wsEDF = Worksheets("edf master")
There is an end sub plus all the variables were declared at the top. Also at one point the macros worked fine. So have gone back to an old version and will look at changing that based on some advice below.
There's no sheet named edf master in the active workbook. Watch for whitespace (leading and/or trailing).
If the active workbook is ThisWorkbook (i.e. the workbook that contains the code that's running), then you don't need any of this.
Look at the Project Explorer (Ctrl+R). Under "Microsoft Excel Objects" you'll find a class module for every single sheet in your workbook. Click one, then hit F4 to display the Properties box.
In the sheet's properties, you'll see it has a (Name) property, which is probably saying something like Sheet1. Change it to something meaningful, e.g. MarexMasterSheet, or MacquarieMasterSheet, or EDFMasterSheet.
Then you don't need wsMarex, wsMQ and wsEDF anymore - they're already declared for you, as global-scope Worksheet instances. So, say the next line of code was this:
Debug.Print wsMarex.CodeName
Now you can do this instead:
Debug.Print MarexMasterSheet.CodeName

Reference an excel sheet from another workbook without copying the sheet

Im wondering if it's possible to reference an excel sheet from another work book without making a copy of that sheet?
The situation : I have some very large worksheets filled with various data, but i don't want to keep a copy of them open in my workbooks because while each workbook uses the same data source, they're slightly different.
I have a vba routine that takes this data and creates input files for other codes, vba expects this data to be available on the defined sheet names.
Is it possible to make either excel or vba to know that when i request worksheet("Example_1") it instead knows that i mean example_1 from a different workbook?
Thanks
Yes, it is possible.
You need to add those lines to your code:
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set wkb = Excel.Workbooks("name_of_workbook.xlsx")
Set wks = wkb.Worksheets("Example_1")
Now, every time you want to refer to a range from this other workbook, you need to add wks. before, i.e.:
'Printing value in cell.
wks.Range("A1") = "x"
'Selecting range.
call wks.Range(wks.Cells(1,1), wks.Cells(2,2)).Select
=SUM('C:\test\[test.xlsx]sheet_name'!A1:A25)
is an example of a formula which references sheet sheet_name in workbook C:\test\text.xlsx.
Note that when the other workbook is opened, the formula automatically changes to
=SUM([test.xlsx]sheet_name!A1:A25)
and then when it is closed, the formula will change back.

VBA logic when using macros from personal.xls

I run a spreadsheet report that holds about 50 columns of data for anywhere from 1 to 5000 rows. I'm only interested in 4 columns, but they are never in the same location as these reports are set-up a bit differently for each client. I then take those 4 columns and paste into a new workbook that I can import into another program.
I have three macros created that accomplish this task flawlessy if ran from the local file. When I load them into the personal.xls for use on various files I have issues. Specifically workbook/worksheet referencing issues.
Parts of the macro run to the sheet I intend from them to result on, while other parts act on the personal.xls file itself. This confuses me because I don't have any lines that use commands such as 'thisworkbook' or 'activeworksheet'.
For example:
- The first line is coded to rename Sheet1. The macro renames Sheet1 in personal.xls.
- The next line is the first of four Find commands that locate where the columns i'm interested are located and then move them. This macro runs perfectly on the sheet I intend.
I think my best course is to begin each macro by naming the active workbook and then breaking out each command to the workbook level instead of starting with Worksheets, Range, etc.
Can anyone help me understand what VBA is thinking when performing macros from personal.xls and how to best avoid the macros being run on that sheet itself?
There are two approaches you can take. I use one or both in my code - it's not a one or the other situations.
Declare Variables
Start by defining each sheet that you want to work on in a variable. I generally stay at the sheet level, but that's just a personal choice. If you'd rather be at the workbook level, that's OK too. A procedure might looks like:
Dim shSource as Worksheet
Dim shDest as Worksheet
Set shSource = Workbooks("SomeBook").Worksheets(1)
Set shDest = ActiveWorkbook.Worksheets("Summary")
then whenever I reference a Range or Cells or anything else on a sheet, I preface it with that sheet object variable. Even if I need to get to the workbook, I start with the sheet. If I needed to, for instance, close the Source workbook from the above example, I would use
shSource.Parent.Close False
I set up the sheet variables I need and then everything I do is in terms of those variables.
Edit
If you're opening or creating workbooks, then variables is definitely the way to go. For example, if you're opening a workbook, you could use one of these two examples
Dim wb As Workbook
Set wb = Workbooks.Open(C:\...)
Dim ws As Worksheet
Set ws = Workbooks.Open("C:\...).Worksheets(1)
or creating new, one of these two examples:
Dim wb As Workbook
Set wb = Workbooks.Add
Dim ws as Worksheet
Set ws = Workbooks.Add.Worksheets(1)
With Blocks
When I'm only trying to get at something one time, it seems like a waste to set up a bunch of variables. In those cases, I use a With Block so I can still have fully qualified references, but without a bunch of clutter in my code.
With Workbook("MyBook")
With .Worksheets("First_Sheet")
.Range("A1").Value = "stuff"
End With
With .Worksheets("Second_Sheet")
.Range("G10").Formula = "=A1"
End With
End With
I probably prefer the variable method, but I use them both.
Edit 2: Implicit Referencing
You should always explicitly reference your workbooks and worksheets, but it's still instructional to know how Excel will behave if you don't. A line of code that starts like Range("A1").Value = ... is called an unqualified reference. You're referencing a range, but you're not saying which sheet its on or which workbook that sheet is in. Excel handles unqualified references differently depending on where your code is.
In a Sheet's Class Module (like where you use sheet events like SelectionChange), unqualified references refer to the sheet represented by that module. If you're in the Sheet1 module working in the Change event and you code x = Range("G1").Value then the G1 you are referring to is on Sheet1. In this case, you should be using the Me keyword rather than relying on Excel.
In any other module (like a Standard Module), unqualified references refer to the ActiveSheet. The same x = Range("G1").Value code in a Standard Module refers to G1 on whichever sheet has the focus.
Excel's treatment of unqualified references is very reliable. You could easily create robust code by relying on Excel to resolve the qualified references. But you shouldn't. Your code will be more readable and easier to debug if you qualify every reference. I qualify every reference. And that's not one of those things I "always" do except when I'm lazy - I really do it 100% of the time.

Vb.net Updating excel formula with references to other workbooks

I am trying to update some formulas from one workbook, to another workbook. Everything is working great until I run into a formula that has a reference to another workbook. For example a formula like this =IF(ISERROR(W!Var1),0,W!Var2) It will prompt me to open this workbook, I am assuming so that it can evaluate the formula. So my question is this. Is there a way for me to handle these situations on the fly, so if there is a workbook reference needed it will prompt me and then save it to memory? Because if I have more than one cell that contains these formulas it will prompt me to open the referenced workbook for every cell that contains the link. Alternatively, is there a way that I can just push my formula into the cell without having excel evaluate it?
So in my code I have this line which works for any value that doesn't contain a workbook reference. TheRange.RefersToRange.FormulaR1C1 = RangeFormula
Any help is greatly appreciated.
I understand that you refer to Worksheets (each of the "tabs" in a given Excel file), the Workbook is the whole file. The popping-up message appears when the referred Worksheet cannot be found. Example: range.Value = "=sheet5!A3" (in a Workbook having just "sheet1", "sheet2" and "sheet3"). If you want to avoid this message (although bear in mind that the Worksheet is not there and thus the calculations will be wrong anyway), you can write:
excelApp.DisplayAlerts = False
Where excelApp is the Excel.Application you are currently using.

Why do I get an HRESULT 0x800A03EC when using Worksheets.Visible?

I've been trying to figure out ways to tell the difference between instances of excel that load the worksheets and ones that don't
Currently I use code to open existing files that looks something like that:
Dim wkbWorkBook as Excel.Workbook
Dim objExcel As Excel.Application
wkbWorkBook = System.Runtime.InteropServices.Marshal.BindToMoniker(filename)
objExcel = wkbWorkBook.Parent
'To make the excel app visible while working with it:
objExcel.Visible = true
What i've noticed while using this code is that If I open a file that exists, but isn't open in excel, when I make the Excel Application visible, the Worksheets aren't visible, but they do exist (I can access worksheets.count and there is an appropriate number of sheets)
I try using Worksheets.Visible but I've noticed it only has an HRESULT error in the place where a "Visible" value would be.
The same error occurs when I try to get the Visible property even when the worksheets are visible (in cases when I BindToMoniker() a file that is currently open in excel.. )
Part of my question is why the BindToMoniker() + Application = workbook.Parent is always giving me an Excel Application without any sheets loaded.. I can't work with it when it's like that..
without gurantees, but I would say worksheets.visible -> won't work, becasue worksheets gives you a list of worksheets.
You cannot apply .visible on that -> you would have to use worksheets(1).visible
Additionally, if there aren't any worksheets, this should fail anyways. you would have to check your count of worksheets first.
Another thing - i don't know if this is possible under vb.net with interop, but maybe you can access specific worksheets through their internal codename - like this:
pobjExcel.table1.visible