I am trying to hide the activecell column across first 4 tabs. The vba below does not seem to be working. It only hides the activecell in first tab in activesheet. So basically I select highlight first 4 tabs and select cell A1 then use below code:
ActiveCell.EntireColumn.Hidden = True
This only hides column A in first tab, but not tab 2,3,4. Can someone please help get the correct code? Just fyi...it has to be the selected cell and not Range("A1").EntireColumn.Hidden = True, because cell can be any active cell I am trying to hide using an offset function. Any help is appreciated. Thanks.
You could store the location of the active cell, then cycle through each worksheet and use that location to base your column hiding..
Sub tested()
Dim cell_address As String
Dim wsName, ws, c As Range
cell_address = ActiveCell.Address
wsName = Array("Sheet1", "Sheet2", "Sheet3", "Sheet4")
For Each ws In wsName
Sheets(ws).Range(cell_address).EntireColumn.Hidden = True
Next
End Sub
Hide the Same Column in Different Worksheets
There is no way to combine (select) cells from multiple worksheets at the same time so you need to loop through the worksheets and hide each column separately, one after the other.
Usage
Sub HideCellColumnsTEST()
Dim wsIDs(): wsIDs = Array(1, 2, 3, 4)
Dim ws As Worksheet: Set ws = ActiveSheet
Dim cell As Range: Set cell = ws.Range("A1")
'or:
'Set cell = ActiveCell
'Set cell = ActiveCell.Offset(, 3) '...etc.
HideCellColumns cell, wsIDs
End Sub
The Method
Sub HideCellColumns(ByVal cell As Range, ByVal wsIDs As Variant)
Dim CellAddress As String: CellAddress = cell.Address
Dim wb As Workbook: Set wb = cell.Worksheet.Parent
Dim ws As Worksheet, wsID
For Each wsID In wsIDs
On Error Resume Next
Set ws = wb.Worksheets(wsID)
On Error GoTo 0
If Not ws Is Nothing Then ' worksheet exists
ws.Range(CellAddress).EntireColumn.Hidden = True
Set ws = Nothing ' reset for the next iteration
'Else ' worksheet doesn't exist; do nothing!?
End If
Next wsID
End Sub
Related
My code finds user defined values in an active worksheet, selects, copies them, and then paste them into a separate worksheet. When I incorporate a loop to iterate over a list of values and copy the results into separate tabs the code breaks. The error Object variable not set (Error 91).
Any thoughts?
Sub copy_paste_sheet_names3()
'declare variables
Dim mainworkBook As Workbook
Set mainworkBook = ActiveWorkbook
Dim sheet_name As String
Dim ws As Worksheet
Dim SelectCells As Range
Dim xcell As Object
Set ws = Worksheets("MasterData")
'check each cell in the specific worksheet if the criteria is matching
For i = 1 To mainworkBook.Sheets.Count
sheet_name = mainworkBook.Sheets(i).Name
For Each xcell In ws.UsedRange.Cells
If xcell.Value = sheet_name Then
If SelectCells Is Nothing Then
Set SelectCells = Range(xcell.Address)
Else
Set SelectCells = Union(SelectCells, Range(xcell.Address))
End If
End If
Next
'select the cells with specified value
SelectCells.EntireRow.Select
SelectCells.EntireRow.Copy
Sheets(sheet_name).Select
Range("A1").Select
ActiveSheet.Paste
ws.Select
Next i
End Sub
I'm using the code below to duplicate a template sheet and give it a couple of characteristics according to the selected cell's content. It works fine up to a point, but since it contains a chart, the resulting sheet's chart is grabbing data from different ranges, than the ones set in the template sheet:
Sub AddSheets()
Dim cell As Excel.Range
Dim allShares As Excel.Worksheet
Dim wbToAddSheetsTo As Excel.Workbook
Dim destTicker As Range
Dim startDate As Range
Dim endDate As Range
Dim sheetName As String
Dim sh 'As Sheets
Set allShares = ActiveWorkbook.Worksheets("all shares")
Set wbToAddSheetsTo = ActiveWorkbook
Application.ScreenUpdating = False
If Selection.Column > 1 Then
MsgBox "Please make sure you Select at least a ticker in column A"
Exit Sub
Else
For Each cell In Selection
With wbToAddSheetsTo
For i = 1 To ActiveWorkbook.Worksheets.Count
If Worksheets(i).Name = cell.Value Then
MsgBox "This name Is already in use!"
Worksheets(cell.Value).Activate
Exit Sub
End If
Next
allShares.Copy After:=.Sheets(.Sheets.Count)
ActiveSheet.Name = cell.Value
ActiveSheet.Range("G4").Value = cell.Value
ActiveSheet.Range("J4").Formula = "='all shares'!$J$4"
ActiveSheet.Range("J5").Formula = "='all shares'!$J$5"
ExtractData
On Error GoTo 0
End With
Next cell
wbToAddSheetsTo.Worksheets("List of Stocks").Activate
End If
Application.ScreenUpdating = True
End Sub
I'm not sure I'm missing something here.
Thanks.
I would like to select multiple cells based on selection.
And here is my code:
Private Sub CommandButton1_Click()
Selection.EntireRow.Select
End Sub
I want to select the first four columns of rows in multiple cells, instead of the whole rows. How to achieve it?
this is my Excel worksheet
Select Rows of Non-Contiguous Range
Copy the codes into a standard module e.g. Module1.
In your command button click event use either of the procedure names in the following way:
Private Sub CommandButton1_Click()
selectRowsOfListObject
End Sub
or
Private Sub CommandButton1_Click()
selectRowsOfFirstFourColumns
End Sub
The first procedure will select only the rows of the selected cells in the first (structured) table in the ActiveSheet. Any cells outside the data of the table (DataBodyRange) will be ignored.
The second procedure will select all the row ranges of the selected cells in the first four columns, in the first four columns of the ActiveSheet. Any cells selected outside of the first four columns will be ignored
Each or both of the codes can be used with command buttons on any worksheet when they will refer to the worksheet 'containing' the command button.
If you want a command button on another worksheet to always refer to the first, you will rather have to create a reference to the first worksheet:
Instead of
Set ws = ActiveSheet
use e.g.
Set ws = wb.Worksheets("Sheet1")
To better understand the differences, you could add another command button for the second code and then test each of them.
The Code
Option Explicit
Sub selectRowsOfListObject()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = ActiveSheet
Dim tbl As ListObject
Set tbl = ws.ListObjects(1)
If Selection.Worksheet.Name = ws.Name Then
If TypeName(Selection) = "Range" Then
Dim rng As Range
Set rng = Intersect(Selection, tbl.DataBodyRange)
If Not rng Is Nothing Then
Set rng = Intersect(rng.Rows.EntireRow, tbl.DataBodyRange.Rows)
End If
If Not rng Is Nothing Then
rng.Select
End If
End If
End If
End Sub
Sub selectRowsOfFirstFourColumns()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = ActiveSheet
If Selection.Worksheet.Name = ws.Name Then
If TypeName(Selection) = "Range" Then
Dim rng As Range
Set rng = Intersect(Selection.Rows.EntireRow, _
ws.Columns(1).Resize(, 4))
If Not rng Is Nothing Then
rng.Select
End If
End If
End If
End Sub
Check this code:
Option Explicit
Sub Rows_Selection()
Dim rng As Range
Dim active_cells_adress, row_no As Variant
Dim final_selection_adress As String
Dim rng1 As String
Dim i As Integer
Selection.EntireRow.Select
Set rng = Selection
rng1 = rng.Address
final_selection_adress = ""
active_cells_adress = Split(rng1, "$")
For i = 2 To UBound(active_cells_adress)
row_no = Split(active_cells_adress(i), ",")
final_selection_adress = final_selection_adress + "A" & row_no(0) & ": D" & row_no(0) + ","
i = i + 1
Next
final_selection_adress = Left(final_selection_adress, Len(final_selection_adress) - 1)
Range(final_selection_adress).Select
End Sub
I have an excel file with a list of names(names.xlsm), I want to create another new excel file(separate.xlsx) with different sheets. The name of each sheet in separate.xlsx is a name in names.xlsx and the first cell of each sheet is the same name value.
'''VBA
Sub copy_name()
Dim MyCell As Range, MyRange As Range, ws As Worksheet
Dim mybook As Workbook
Set mybook = Workbooks("names.xlsm")
Set MyRange = mybook.Sheets("names").Range("A2:A6") 'eg. five names'
Dim target As Workbook
Set target = Workbooks("separate.xlsx")
i = 1
For Each MyCell In MyRange
Set ws = target.Worksheets.Add(After:=Worksheets(Worksheets.Count)) ' create new worksheet in target file
ws.Name = MyCell.Value ' renames the new worksheet
target.Sheets(MyCell.Value).Cells(1, 1) = MyCell 'copy the value of Mycell to target sheets
i = i + 1
Next
Set mybook = Nothing
Set target = Nothing
End Sub
'''
Here is my code. It keeps showing errors and I do not know how to debug.
You can create the worksheet and name it in one line. No need to create it and then name it.
You need to fully qualify your objects
I am assuming that the workseets with the same name as in the names.xlsm do not exist in separate.xlsx. If it does then you will have to handle that separately.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim wbNames As Workbook, wbSep As Workbook
Dim rng As Range, aCell As Range
Set wbNames = Workbooks("names.xlsm")
Set wbSep = Workbooks("separate.xlsx")
Set rng = wbNames.Sheets("Names").Range("A2:A6")
For Each aCell In rng
With wbSep
.Sheets.Add(After:=.Worksheets(.Worksheets.Count)).Name = aCell.Value
.Worksheets(aCell.Value).Cells(1, 1).Value = aCell.Value
End With
Next
End Sub
I must jump between different excel sheets to grab data for my VBA to output what I want. I've been using the Sheets("name").Select function to jump between the sheets. Sometimes it works and lets me run the program, but other times I get a runtime error. I want this to work 100% of the time every time, and always get disheartened whenever it fails due to the select function. If anyone has any tips or recommendations I would love for you to share them! Any help would be greatly appreciated.
Sheets("Test").Select
Run-time Error '1004': Select Method of Worksheet Class Failed
Don't use Select (or Activate for that matter), it's bad practise and leads to errors rather quickly.
This thread is a great help as to why and how you should avoid using it.
There is no need to select a sheet before getting data from it. For example:
Sub test()
'''
'Bad practise:
'''
Sheets("Sheet1").Select
i = Range("A1")
'''
'Good practise
'''
i = Workbooks("Book1").Sheets("Sheet1").Range("A1").Value
'''
'Better practise
'''
Dim wb As Workbook
Dim sht As Worksheet
Dim i As String
Set wb = Workbooks("Book1")
Set sht = wb.Sheets("Sheet1")
With sht
i = .Range("A1").Value
End With
End Sub
With Statement:
Option Explicit
Sub test()
'Create a witrh statement with the Sheet name you want
With ThisWorkbook.Worksheets("Sheet1")
'Refer to cell A1 (don t forget the "." before Range)
.Range("A1").Value = ""
'Refer to cell A1 (don t forget the "." before Cells)
.Cells(1, 1).Value = ""
End With
End Sub
Loop Worksheets:
Option Explicit
Sub test()
Dim ws As Worksheet
'Loop Sheets
For Each ws In ThisWorkbook.Worksheets
With ws
'If sheet name is Sheet1 or Sheet3
If .Name = "Sheet1" Or .Name = "Sheet3" Then
'Refer to cell A1 (don t forget the "." before Range)
.Range("A1").Value = 2
'Refer to cell A1 (don t forget the "." before Cells)
.Cells(1, 1).Value = 10
ElseIf .Name = "Sheet2" Then
'Refer to cell A1 (don t forget the "." before Range)
.Range("A1").Value = 5
'Refer to cell A1 (don t forget the "." before Cells)
.Cells(1, 1).Value = 20
End If
End With
Next ws
End Sub
Set Worksheet To Variable
Option Explicit
Sub test()
Dim ws1 As Worksheet, ws2 As Worksheet
With ThisWorkbook
Set ws1 = .Worksheets("Sheet1")
Set ws2 = .Worksheets("Sheet2")
End With
End Sub