How to call a macro from a sheet object - excel

I have a template file that connects to oracle and want to make a simple macro to refresh the oracle connection in every sheet, and I'll make a separate batch update file to open each of these files and call that macro. The X = HypMenuVRefreshAll() didn't work, so I tried X = HypMenuVRefresh(), and it only worked if I put it in the sheets themselves.
Can I have a module that loops through each of the sheets and calls that macro?
So I have something like this:
(The if statement is because the only sheets connected start with "CC ")
Sub Refresh_Workbook()
For Each Worksheet In ThisWorkbook.Worksheets
If Left(ws.Name, 3) = "CC " Then
Call EPBCS_Refresh_This_Sheet
End If
Next Worksheet
End Sub
And the Refresh sheet code looks like this(This works fine if I run it on it's own):
Public Sub EPBCS_Refresh_This_Sheet()
X = HypMenuVRefresh()
End Sub
But the module code is giving an error, because the sub i'm trying to call is undefined.
I think I could provide the sheet names specifically and call it that way, but the problem is that this is a template. So the sheet names need to be variable if that were the case so others can use this.
Any ideas?
I tried X = HypMenuVRefreshAll() and I got errors relating to other things in the file, so I tried X = HypMenuVRefresh() and that works only if I run it within the sheet object, not in the module object. I'm thinking when I try to run it in a module, it runs into other things, but in the sheet there's really no other code to interfere.
So I need to activate each sheet (variable name because this is a template), and run the code within that sheet's object.

Related

Excel AddIn using Name Manager

at work we have some add-ins. Someone got the idea to rename a Sheet, whereupon the Script no longer work. To prevent this from happening in the future, I put the following formula in the worksheet and gave the cell a name using the Name Manager
=TEIL(ZELLE("dateiname";A1);SUCHEN("]";ZELLE("dateiname";A1))+1;31)
In VBA I use the following script:
fileName = "Filename.xlam"
Test = Workbooks (fileName) .Application.Names ("Test")
If I set temporarily the isAddIn value to False, everything works without any problems. As an add-in, however, I get error 1004. Can someone help me?
It should be great, if the possibility to get the file name of the xlam add-in via a function, in case someone else comes up with the brilliant idea of renaming this file.
Many thanks for your help
Sam
I use this method to lock my sheet names: Add this to the worksheet code that you want to lock and then save the sheet. If a user tries to edit the name it will simply revert back to its original name.
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
If ActiveSheet.Name <> "test" Then
ActiveSheet.Name = "test"
End If
End Sub
source

Is it not a good Idea to use the Set Worksheets method multiple times during code execution?

I am attempting to copy different images to different worksheets of my Workbook using the following code below. I am changing the Target Worksheet Dynamically in a different sub, with a String Variable in the Global Declarations section. I can see the variable being passed to the sub and in fact it works the first pass through the code, but when I attempt to change the "TargetSheetIni" variable to a new sheet, it continues to use the first original sheet as it loops through.
Can you not change a target sheet after using the Set keyword? Should I refer to the sheet directly instead?
Sub Test1()
Dim TargetWS, SourceWS As Worksheet
Set TargetWS = Worksheets(TargetSheetIni)
Set SourceWS = Worksheets("Images")
DoEvents
SourceWS.Shapes(CurrentImageId).Copy
DoEvents
TargetWS.Paste Range(ColumnLetter2 & RwCnter)
DoEvents
End Sub
I think I may have figured it out. As far as I can tell the issue may be that I used the Copy Sheet Functionality in Excel when I originally created the target sheets. And even though I renamed the sheets both on the tab below and in the project editor... for some reason VBA kept targeting only the original sheet
I proved this by changing my code around to explicitly call the sheet I wanted to target like so:
ActiveWorkbook.Worksheets("Sheet2").Paste Range("I2")
And even doing that it would target sheet 1 for the paste command instead of the expected sheet 2. I deleted the three copy sheets and created a new one from scratch and re-executed code and now it targets sheet 2 as expected.
I found this article that sort of explains it I guess...
https://www.spreadsheetsmadeeasy.com/7-common-vba-mistakes-to-avoid/
Ok my last answer may have not been correct. It appears as though for some reason inserting an ws.activate caused my code to start workin.g
Very frustrating fix. as I have always heard to avoid using that.

function not recognizing macro input for sheet name

I'm looking to reformat a program's export. So far I've created a function that calls for a single string input, which is simply a number identifier (2210-01, for example).
This input is causing issues once I go to navigate to the sheet by that name.
I've tried assigning the input datatype as something other than a string, but that's causing other issues. I know that my WB has those sheet names that are in the RunFormatRawExport(), I'm not sure why it's causing issues when I pull open the sheet though.
Sub RunFormatRawExport()
FormatRawExport ("2210-01")
End Sub
Public Function FormatRawExport(ComCode As String)
Sheets("ComCode").Activate
End Function
with this short snippet, the macro should just re navigate to sheet 2210-01. I'm not getting errors when I call for ComCode before this error.
It could be that you should first set focus to the workbook the sheet "CombCode" is in, i.e. Workbooks([name]).Activate

Insert VBA sub into Excel Worksheet

Good day,
I am using Excel 2013 and I would like to hide and unhide my Sheets as I work with them. I spent some time Googling around and found plenty of ancient posts on forums about adding VBA to modules, but that's not quite what I'm looking for.
On a main page where I spend most of my time using data, I have a button that shows a UserForm with a list of sheets in a ListBox. I choose the Sheet from the ListBox, hit OK, and it runs the following;
Private Sub OKButton_Click()
ThisWorkbook.Sheets(JobListBox.value).Visible = xlSheetVisible
ThisWorkbook.Sheets(JobListBox.value).Activate
Unload Me
End Sub
I would like it so when I have my new sheets created via VBA, I can populate the sheet with the following subroutine;
Private Sub Worksheet_Deactivate()
Me.Visible = xlSheetVeryHidden
End Sub
If anyone can let me know how I can make a Subroutine to insert this code into my sheets, I would greatly appreciate it.
PS: My fallback method is to, of course, just copy/paste the code manually... But I would prefer to automate it if possible.
Instead of adding the same code to each sheet, since they are all inside the workbook and you are really trying to execute a hide once any sheet in the workbook is deactivated, put this in the code for ThisWorkbook.
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Sh.Visible = xlSheetVeryHidden
End Sub
You might be able to use more workbook events with your type of project.
Here is a list of the workbook events.
If you want to exclude your main page from this, you can modify this by adding an IF statement:
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
IF Sh.Name <> "Main" Then
Sh.Visible = xlSheetVeryHidden
End If
End Sub
The main line of thinking being that if you have to put the same code into more than one object, let alone ALL of them, you are repeating yourself.
Check out the concept of DRY, or "Don't Repeat Yourself", unless you like it WET, "We Enjoy Typing". or "Write Everything Twice". Even if it's just going to be created programmatically, a chunk of code shouldn't have to exist in all your sheets exactly the same when you can have one piece of code have an incoming argument that is a worksheet.
This way, if you have to make a change to its behavior, you do it once. It's easily testable and less to keep track of or modify later.
So if you find yourself having to use the same code over and over, look to the parent object and try to find a way to pass the changing object or variable through as an argument to a singular piece of code, or module.
Also, this is probably why you aren't finding any results on inserting the same code into every sheet. It's not a good practice
Article on DRY

Outside code for Excel 2003 macros

Does someone know how to write VBA code in outside file, which is "imported" into Excel 2003 VBA macro every time you run this macro in Excel - like self updating code?
The idea is I write code in outside editor (VIm), and every time I start Excel macro, macro checks for newer data, import that code inside if necessary and then run it (may be one or more functions/subs).
The steps are: open Excel, open XLS file, click on the button, the macro starts, checks for newer outside data (code I have written in outside editor), if data is new, delete old code, import outside code and then actually run macro itself.
Anyone?
Assuming your using this VIM (a text editor) to write .bas files, you can then use the many, many functions for overwriting modules or procedures from this site Programming the VBE.
So, your structure would like something like this:
Sub MyMacro()
Overwrite MyModule in this Workbook with MyModule in .bas file (you could do line count checks or something if you need to, or just overwrite each time to ensure latest code
Call MyModule
End Sub
There are obvious checks you want to incorporate, I would think, to ensure that your latest code always works with the workbook...
checks for newer outside data (code I have written in outside editor), if data is new, delete old code, import outside code and then actually run macro itself.
Found solution (partly from http://www.cpearson.com/excel/vbe.aspx) 10x Scott:
Sub AddOutsideCode()
Dim VBProjekt As VBIDE.VBProject
Dim VBKomponenta As VBIDE.VBComponent
Set VBProjekt = ThisWorkbook.VBProject
Call DeleteAllButThis(ThisWorkbook, "Fixed")
Set VBKomponenta = VBProjekt.VBComponents.Import(Filename:="C:\bat\bat.bas")
VBKomponenta.Name = "OutsideCode"
End Sub
'Delete all modules but named
Private Sub DeleteAllButThis(ByVal wb As Workbook, ByVal CompName As String)
Application.DisplayAlerts = False
On Error Resume Next
For Each komponenta In ThisWorkbook.VBProject.VBComponents
If komponenta.Name <> CompName Then
If komponenta.Type = vbext_ct_StdModule Then
ThisWorkbook.VBProject.VBComponents.Remove komponenta
End If
End If
Next komponenta
On Error GoTo 0
Application.DisplayAlerts = True
End Sub
But how to check if the outside code changed or not?

Resources