Excel VBA - Add new table columns with specific header names - vba

I have a simple vba question. I want a macro that will add exactly 4 new columns in my table object, ("Table1"). I would also like these to be named in order, from left to right:
AHT, Target AHT, Transfers, Target Transfers
The code I have below adds the columns just fine, but I am not sure how to name one individually. Also, could someone please show me how to loop that section of code. Thanks!
Sub insertTableColumn()
Dim lst As ListObject
Dim currentSht As Worksheet
Set currentSht = ActiveWorkbook.Sheets("Sheet1")
Set lst = ActiveSheet.ListObjects("Table1")
'below is the code that I would like to have looped
lst.ListColumns.Add
lst.ListColumns.Add
lst.ListColumns.Add
lst.ListColumns.Add
End Sub

A variant array is a good place to store the variables in a looped sequence.
Sub insertTableColumn()
Dim lst As ListObject
Dim currentSht As Worksheet
Dim h As Long, hdrs As Variant
hdrs = Array("AHT", "Target AHT", "Transfers", "Target Transfers")
Set currentSht = ActiveWorkbook.Sheets("Sheet1")
Set lst = ActiveSheet.ListObjects("Table1")
With lst 'ActiveSheet.ListObjects("Table1")
For h = 0 To 3
.ListColumns.Add
.ListColumns(.ListColumns.Count).Name = hdrs(h)
Next h
End With
End Sub
When creating an array of strings in this manner, remember that the variant array's index is zero-based by default.

The following code creates an array of the column names you want to add, then loops as many times as there are headers to add and sets the name at the same time.
Sub insertTableColumn()
Dim lst As ListObject
Dim currentSht As Worksheet
Set currentSht = ActiveWorkbook.Sheets("Sheet1")
Set lst = ActiveSheet.ListObjects("Table1")
ColumnNames = Array("AHT", "Target AHT", "Transfers", "Target Transfers")
' below is the code that I would like to have looped
For iLoop = 0 to UBound(ColumnNames)
Set oLC = lst.ListColumns.Add
oLC.Name = ColumnNames(iLoop)
Next
End Sub

Related

Set Range as Found String Location in VBA

I'm trying to set a range in VBA as the range of the inputted string that I am looking for. The full procedure is supposed to pop up a dialog box to look for a specific string, find the string, create a range called location, set this range to the range of the string that was found, move a finite amount of columns to the right, and with that new columns value, print a string into that range.
The problem right now is that for some reason It is not setting the range to the range of the string it finds.
There is only one instance of the string throughout the workbook.
I'm also relatively new to VBA so there are something commands I don't know or understand how they work.
Sub test()
Dim wb As Workbook
Set wb = ActiveWorkbook
Dim Inp As String
Dim Loc As Range
Dim Row As Integer
Dim Col As Integer
Dim NewLoc As Range
Dim Sh As Worksheet
Inp = InputBox("Scan ESD Tag")
For Each Sh In ThisWorkbook.Worksheets
With Sh.Columns("A")
Set Loc = .Find(What:=Inp)
End With
Next
Row = Loc.Row
Col = Loc.Column + (3 * 5)
Set NewLoc = Worksheets("Building 46").Cells(Row, Col)
NewLoc.Value = "Over Here"
Range("G2") = 6
End Sub
Your problem is probably that your final block should be inside the loop as otherwise Loc is likely to be Nothing (unless the term is found on the last sheet) and your code will error. You should also check first that it is found to avoid such errors.
Sub test()
Dim wb As Workbook
Set wb = ActiveWorkbook
Dim Inp As String
Dim Loc As Range
Dim Row As Integer
Dim Col As Integer
Dim NewLoc As Range
Dim Sh As Worksheet
Inp = InputBox("Scan ESD Tag")
For Each Sh In ThisWorkbook.Worksheets
With Sh.Columns("A")
Set Loc = .Find(What:=Inp)
If Not Loc Is Nothing Then
Row = Loc.Row
Col = Loc.Column + (3 * 5)
Set NewLoc = Worksheets("Building 46").Cells(Row, Col)
NewLoc.Value = "Over Here"
Range("G2") = 6 'should specify a sheet here
Exit Sub
End If
End With
Next
End Sub

Hiding rows using VB

My goal is to hide each row that contains a cell filled with red. Here is my code:
Sub AstInv()
Dim myTable As ListObject
Dim myArray As Variant
Set myTable = ActiveSheet.ListObjects("Sheet2")
Set myArray = myTable.ListColumns("Código de Barras2").Range
For Each cell In myArray
If Rng.Interior.Color = vbRed Then
rw.EntireRow.Hidden = True
End If
Next
End Sub
Each time I run it, I get this error:
Compile error: Invalid outside procedure
Please help! Thanks!
Your code is a bit disjointed and attempts to use variables that have not been dimmed or instantiated.
Sub AstInv()
Dim myTable As ListObject
Dim myArray As range
Set myTable = ActiveSheet.ListObjects("Table2")
Set myArray = myTable.ListColumns("Código de Barras2").Range
For Each cell In myArray
If cell.Interior.Color = vbRed Then
cell.EntireRow.Hidden = True
End If
Next
End Sub
There are several issues with your code:
Compile error: Invalid outside procedure
means that you have some random text at the top of your module (outside all Subs), as in:
random ' <- Invalid outside procedure
Sub AstInv1()
Dim myTable As ListObject
Dim myArray As Variant
...
But there are more issues:
It is unlikely that you have a table named "Sheet2"
Your ActiveSheet (the sheet currently visible) may not contain the intended table / ListObject
myArray is declared as Variant when it should be Range
Rng and rw objects are undeclared and, as mentioned, are not connected to any other objects
To fix them
Use Option Explicit - this will force you to declare all variables
Check your objects' names and location
In the code call your objects explicitly
Option Explicit
Public Sub AstInv()
Dim myTable As ListObject
Dim myCol As Range
Dim cell As Range
Set myTable = ThisWorkbook.Worksheets("Sheet2").ListObjects("Table1") 'Check names
Set myCol = myTable.ListColumns("Código de Barras2").Range
For Each cell In myCol
cell.EntireRow.Hidden = (cell.Interior.Color = vbRed)
Next
End Sub
This version uses an AutoFilter and shows how to avoid errors when objects are missing
Option Explicit
Public Sub AutoFilterRedCells()
Dim tbl As ListObject, col As Long
On Error Resume Next 'Ignore expected errors
Set tbl = ThisWorkbook.Worksheets("Sheet2").ListObjects("Table1") 'Check names
col = tbl.ListColumns("Código de Barras2").Range.Column
On Error GoTo 0 'Stop ignoring errors
If col > 0 Then tbl.Range.AutoFilter Field:=col, Operator:=xlFilterNoFill
End Sub

Delete table name in Excel VBA

I would like to remove/delete the name of my table which is "Table2" using Excel VBA. I know how to remove the name by hand, but I cannot figure out how to set the name "Table2" as a name in VBA. I found other questions on this topic but those codes deleted all named ranges and I would like to remove just the table named "Table2".
This is my code that is not working:
Sub Delete_Name_Table()
Dim n As Name
n = "Table2"
n.Delete
End Sub
Anyone who knows how to set n correctly to "Table2"?
Thanks!
You can backup data from table, delete table and restore data.
Sub test()
Dim rng As Range
Dim rngVals As Variant
Set rng = YourSheet.ListObjects("Table2").Range
rngVals = rng.Value
YourSheet.ListObjects("Table2").Delete
rng.Value = rngVals
Set rng = Nothing
End Sub
I hope I understood your post, and you want something like the code below:
Option Explicit
Sub Delete_Name_Table()
Dim Sht As Worksheet
Dim Tbl As ListObject
Set Sht = Worksheets("Sheet1") ' <-- change to your sheet that has the table
' set the Table Object
Set Tbl = Sht.ListObjects("Table2")
Tbl.Name = " " ' clear the name, you need to give it some kind of name
End Sub
There is a good way to make a table to a range. Thus, the name is removed automatically, but the value stays. Like this:
Public Sub TestMe()
Dim tblN As Object
Dim rngRange As Range
For Each tblN In ActiveSheet.ListObjects
Debug.Print tblN
If tblN = "Tabelle16" Then
tblN.Unlist
End If
Next tblN
End Sub
If you want to remove the data within as well, here is the code:
Public Sub TestMe()
Dim n As String
n = "Tabelle2"
Range(n).Delete
End Sub
It will set n to a Table name and it will delete it.

Extracting the item from a DICTIONARY in VBA

I have created a dictionary that stores the sheet name and its number.
So the code is as:
Sub SetDiction()
Dim num as Excel.Range
Dim wks As Excel.Worksheet
For each wks in ThisWorkbook.Worksheets
Set num = Nothing
Set num = wks.Range("SheetNumber")
If not(num is Nothing) Then
rModule.rDictionary.Add:=num.Value Item:=wks
End If
Next
End Sub
Now am trying to get the wks name and put it in another worksheet.The code is:
Sub GetSheet()
Dim key as variant
For each key in rModule.rDictionary.Keys
With Sheet2
.Cells(2,1).Value = rModule.rDictionary.Item(key)
End With
End Sub
It is giving me application defined or Object-defined error.
Can some one help please?
Your .Add call is syntactically incorrect and you are adding the whole worksheet to the dictionary where presumably you just want to add the named range, change to:
rDictionary.Add num.Value, num
To add the name:
rDictionary.Add num.Value, wks.Name

Selecting multiple sheets using a range

I have sheet names in cells C2 to C5, which are dynamic. I would like to select them at the same time using VBA.
The only way I have found uses arrays and "hard-coding" the sheet names.
Sub ssheets()
Worksheets(Array("Sheet2", "Sheet3","Sheet4","Sheet5")).Select
End Sub
I would like something that uses Range("C2:C5") so that I can select the relevant sheets without having to type in "Sheet2", "Sheet3","Sheet4","Sheet5" etc.
The sheet names array has to be of type Variant containing a one dimensional array. The Range("C2:C5") returns a two dimensional array. To use this as sheet names array, you have to transpose it.
Sub ssheets()
Dim oWS As Worksheet
Dim aSheetnames As Variant
Set oWS = Worksheets(1)
aSheetnames = oWS.Range("C2:C5")
aSheetnames = Application.WorksheetFunction.Transpose(aSheetnames)
Worksheets(aSheetnames).Select
End Sub
Try this:
Sub Macro1()
Dim sheetArray() As String
Dim i As Integer
i = 0
For Each c In Range("C2:C5").Cells
ReDim Preserve sheetArray(0 To i)
sheetArray(i) = c.Value
i = i + 1
Next
Sheets(sheetArray).Select
End Sub
You may also consider adding verification if the sheet with that name exists before adding it to array.
3 lines of code needed (2, if you want ActiveSheet selected as well):
Sub sSheets()
Set xRange = Range("C2:C5") 'define ur range
Sheets(xRange.Cells(1).Value).Select 'this is only needed to de-select the ActiveSheet
For Each xCell In xRange: Sheets(xCell.Value).Select False: Next '[False] is like holding Ctrl and clicking on different tabs
End Sub