I need to insert tab name in cell A1 of every tab with changing tab names - vba

I need to open a worksheet with a fixed name and insert the name of each tab (which will change according to the current date) at the top of the sheet.
I modified some code from a previous answer and had the code working when it did not include the code to open the workbook. Now it flicks through the tabs but doesn't insert the name into Cells(1, 1) and I have no idea why. It also bugs at the end: Run-time error 91, which is less problematic but would be good to fix.
Any tips or advice much appreciated. Below is my current code:
Sub PSOPENTAB()
ChDir "G:\directory"
Workbooks.Open Filename:="G:\directory\filename.xls"
Windows("filename.xls").Activate
ActiveWorkbook.Worksheets(1).Activate
Call nametop
End Sub
Sub nametop()
Dim i As Long
With ThisWorkbook
'exit if Activesheet is the last tab
If .ActiveSheet.Index + 1 > .Worksheets.Count Then
Exit Sub
End If
For i = .ActiveSheet.Index To .Worksheets.Count - 1
.ActiveSheet.Cells(1, 1) = .Worksheets(i).Name
ActiveSheet.Next.Select
Next i
End With
End Sub

You need to reference your objects correctly.
Your problems are:
You use Thisworkbook in your nametop routine. So it will always work on the workbook containing the code.
You can change it to ActiveWorkbook but that may lead you to other problems in the future. See this cool stuff to know more about why to avoid Activeworkbook/Activesheet and the like
Applying what's discussed there, try below code:
Sub PSOPENTAB()
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:="G:\directory\filename.xls")
nametop wb
End Sub
Sub nametop(wb As Workbook)
Dim ws As Worksheet
For Each ws In wb.Worksheets
ws.Cells(1, 1) = ws.Name
Next ws
End Sub
Above code adds the name of the sheet in Cell A1 of every sheet.
Is this what you're trying?

Related

VBA How to fix: "Property or method is not supported with this object" when cell securing in multiple sheets

So bassicaly I want to secure a specific range within every sheet (same range always applies).
Code:
Sub desecure()
For x = 1 To ActiveWorkbook.Sheets.Count
ActiveWorkbook.Sheets(x).Range("C7:P16").Protect Password:="30713"
Next
End Sub
Sub secure()
For x = 1 To ActiveWorkbook.Sheets.Count
ActiveWorkbook.Sheets(x).Range("C7:P16").Protect Password:="30713"
Next
End Sub
It always give the error stated in the question. Anyone knows how to fix this? (or a alternative)
You can't protect a range - you set ranges to either "locked" or "unlocked" and then protect the whole sheet
To begin with, all cells are set to locked, but as the spreadsheet isn't protected this has no affect. In your case (assuming you want to be able to change other cells), you would need to unlock every other cell, lock the range you want to prevent changes in, and then protect the sheet. So
Sub secure()
dim ws as worksheet 'i change this line - typo
For each ws in worksheets
ws.cells.locked=false
ws.Range("C7:P16").locked=true
ws.Protect Password:="30713"
next ws
End Sub
Sub Desecure
dim ws as worksheet
For each ws in worksheets
ws.unprotect "30713"
Next ws
End Sub

VBA For Loop Only Altering One Sheet

I'm trying to alter the values in a range of cells for specifically named worksheets only.
The workbook I am editing has around 95 sheets, and I only want to change the sheets with the period actual information (named P1W1, P1W2 etc, up to P12W5).
When i execute the below it only alters the first sheet and then exits the macro.
Any help is much appreciated
Option Explicit
Public Sub periodclear()
Dim ws As Worksheet
Dim r As Range
On Error Resume Next
Set r = Range("c10:i30")
For Each ws In Worksheets
If ws.Name Like ("P#W#") Or ws.Name Like ("P##W#") Then
r.Value = ""
End If
Next ws
End Sub
Try this. Your r was defined only in terms of one sheet so needs to be brought inside the loop.
Public Sub periodclear()
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name Like ("P#W#") Or ws.Name Like ("P##W#") Then
ws.Range("c10:i30").ClearContents
End If
Next ws
End Sub

VBA Hide all sheets that aren't being used in workbook

I have many sheets in a workbook. I have a main sheet/"form" called "JE" and on that sheet there are buttons and macros that lead to other sheets in the workbook. But, the intention is for other users, not myself, to use the workbook. So, I would only like the sheet that is being used to be visible at any given time. At no time do I want more than 1 sheet to be visible by the user. The user can navigate the workbook mainly thru clicking buttons and certain cells in select sheets that will allow them to navigate throughout the entire workbook. I have tried this by adding code into 'ThisWorkbook' module but it doesn't seem to working as I'd like. When I navigate to one sheet and back to another, some sheets remain visible when I'd like them to be hidden so I'm unsure of what other modifications I can make to code below to get my desired result. If anyone can offer up any modifications or changes I can make to accomplish this, I'd really appreciate it.
UPDATE:
I have added this code to my 'ThisWorkbook' Object:
Option Explicit
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySh As Worksheet
For Each MySh In ThisWorkbook.Worksheets
If MySh.Name <> Sh.Name Then MySh.Visible = 0
Next MySh
End Sub
but, when I go to double-click values that usually populate cells in my main sheet ("JE") I get a run-time 1004 error. The values still populate the main sheet but it no longer navigates back to the main sheet as I'd like.
If anyone knows of a solution or a mod I can make, I'd really appreciate it.
The code is nice. Simply put it in the Workbook part of the VBA project:
Option Explicit
Private Sub Workbook_Open()
Dim MySh As Worksheet
For Each MySh In ThisWorkbook.Worksheets
If MySh.Name = ActiveSheet.Name Then MySh.Visible = xlSheetHidden
Next MySh
End Sub
The ThisWorkbook part is here:
In general, I use always something similar, when I am starting an Excel application. I define two Arrays with Visible and Invisible Worksheets and I iterate over them, making them either visible or not visible. Like this:
Option Explicit
Public Sub HideNeeded()
Dim varSheet As Variant
Dim arrVisibleSheets As Variant
Dim arrHiddenSheets As Variant
arrVisibleSheets = Array(Sheet1)
arrHiddenSheets = Array(Sheet2, Sheet3)
For Each varSheet In arrVisibleSheets
varSheet.Visible = xlSheetVisible
Next varSheet
For Each varSheet In arrHiddenSheets
varSheet.Visible = xlSheetVeryHidden
Next varSheet
End Sub
xlSheetVeryHidden makes it possible to unhide it only from the VB Editor. Otherwise you need xlSheetHidden.
It should be Workbook_SheetActivate:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySh As Worksheet
For Each MySh In ThisWorkbook.Worksheets
If MySh.Name <> Sh.Name Then MySh.Visible = 0 'zero - false, 1 - true, 2 - very hidden
Next MySh
End Sub
Sub HideInactive()
Set theActiveSheet = ActiveSheet
For Each Sheet In ThisWorkbook.Worksheets
If Sheet.Index <> theActiveSheet.Index Then Sheet.Visible = False
Next
End Sub
I 've test the code. Thank you for reading.

Copy Paste Across Worksheets (VBA)

I don't know why, I just can't get this to work. I've simplified it right down to just three lines - but it's causing me problems still.
Basically I want to open a workbook and copy some data from it into a master workbook.
I have:
Sub copypaste()
Workbooks.Open("...Test.xlsx").Sheets("Sheet1").Cells(1, 1).Copy
ActiveWorkbook.Close
Sheets("Sheet1").Range("A1").PasteSpecial xlPasteValues
End Sub
I've seen runtime error 438 (object does not support this property method), I can get paste that but just hit 1004 application defined error or object defined error.
I honestly have no idea where I'm going wrong on this simple task!
Thank you in advance,
Tom
Try closing the workbook after pasting the data.
As an example you can use something like:
Sub copypaste()
Dim WBopen As Workbook, Wb As Workbook
Set Wb = ActiveWorkbook
Set WBopen = Workbooks.Open("...Test.xlsx")
WBopen.Sheets("Sheet1").Cells(1, 1).Copy
Wb.Sheets("Sheet1").Range("A1").PasteSpecial xlPasteValues
WBopen.Close
End Sub
Because you are closing the Workbook before the data is pasted it fails.
It is also preferred to not use .Copy and .Paste when it can be avoided.
See example below for a direct setting of the Values:
Sub copypaste()
Dim wbMaster As Workbook, wbData As Workbook
Set wbMaster = Workbooks("Master.xlsm")
Set wbData = Workbooks.Open("Data.xlsx")
wbMaster.Sheets("Sheet1").Range("A1").Value = wbData.Sheets("Sheet1").Range("A1").Value
wbData.Close False
End Sub

excel vba insert column runtime error 1004

this is my first post on StackExchange! I've been using StackExchange for answers, but now i really have a question.
I am trying to add a column in excel using vba. This is procedure is part of a bigger sub function of which I created a new workbook and copy a series of sheets from a different workbook over.
Workbooks.Add
Set TTB = ActiveWorkbook
'add a bunch of sheets here
'sheetName = specific_sheet
Set ttb_sheet = TTB.Sheets(sheetName)
ttb_sheet.Columns("I:I").Insert Shift:=xlToRight
With this i get a runtime error of 1004: 'Insert method of Range class failed'
I tried following a series of questions on StackOverflow...
Select method of Range class failed via VBA
VBA error 1004 - select method of range class failed
It seems like the solution is to select the sheet first, then select the range. I have tried this and there was no luck. Anyone have any insight?
Here's my main sub code..
Sub create_TTB_workbook(TTB_name_)
'create TTB workbook
Dim wsHelper As New WorksheetHelper
Dim final_TTB As Workbook
Dim ttb_sheet As Worksheet
ttb_wb = ActiveWorkbook.name
Workbooks(ttb_wb).Activate
PCB_tab = 0
ST_COMP_tab = 0
For Each WS In Worksheets
If WS.name = "PCB_PIN_REPORT" Then
PCB_tab = 1
End If
If WS.name = "ST_PIN_REPORT" Then
ST_COMP_tab = 1
End If
Next WS
Workbooks.Add
Set TTB = ActiveWorkbook
new_ttb_wb = TTB.name
Debug.Print (new_ttb_wb)
If PCB_tab = 1 Then
wsHelper.copySheet ttb_wb, "PCB_PIN_REPORT", new_ttb_wb, "PCB_PIN_REPORT"
End If
If ST_COMP_tab = 1 Then
wsHelper.copySheet ttb_wb, "ST_PIN_REPORT", new_ttb_wb, "ST_PIN_REPORT"
End If
wsHelper.copySheet ttb_wb, TTB_name_, new_ttb_wb, TTB_name_
' TRIED A BUNCH OF METHODS here...
'Workbooks(ttb_wb).Sheets(TTB_name_).Cells.copy
'Sheets.Add.name = TTB_name_
'ActiveSheet.paste
'Sheets(TTB_name_).Activate
'Columns("I:I").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'Worksheets(TTB_name_).Range("I1").EntireColumn.Insert
'Columns("I:I").Select
'Columns("I:I").Insert Shift:=xlToRight
Set ttb_sheet = Sheets(TTB_name_)
ttb_sheet.Columns("I:I").Insert Shift:=xlToRight
Columns("K").copy Destination:=Range("I1")
Range("I6") = "header name"
End Sub
Whenever I run into an issue like this, I always isolate the code to its simplest form. Once I get it working at that level, I add it back in to the full application and can usually figure out what I did wrong.
I've written a simple version of what you are trying to do. Note that I've included a few Debug.Print statements to help me verify what is going on. The debug messages will appear in your Immediate window. Obviously you can also step through the code and examine variables as you go.
To get this to work, create a workbook and save it as DestinationWorkbook.xlsx. Then open another workbook and insert the code below.
Sub InsertColumnInDestinationWorksheet()
Dim sourceWb As Workbook
Dim targetWb As Workbook
Dim sourceWs As Worksheet
Dim targetWs As Worksheet
Set sourceWb = ThisWorkbook
Debug.Print sourceWb.Name
Set targetWb = Workbooks("DestinationWorkbook.xlsx")
Debug.Print targetWb.Name
Set sourceWs = sourceWb.Sheets("Sheet1")
Debug.Print sourceWs.Name
Set targetWs = targetWb.Sheets("Sheet1")
Debug.Print targetWs.Name
targetWs.Range("I1").Value2 = "Moving right along..."
targetWs.Columns("I:I").Insert shift:=xlToRight
End Sub
After running the code, you can examine the target sheet. You should see the text we wrote into column I is now in column J.
This works for me when I change the variable naming to:
Sub testingg()
Dim ttb_sheet As Worksheet
Set ttb_sheet = Sheets(1)
ttb_sheet.Columns("I:I").Insert Shift:=xlToRight
End Sub
So I presume there's an issue with the way you reference the workbook when setting ttb_sheet on line 3. Note that you add a workbook but you aren't actually 'activating' it necessarily. And are you sure the 'Sheetname' actually exists in the TTB workbook?