Add headers to column data using a macro - vba

I'm in need of a simple macro that adds the column header values to the contents in the columns of a spreadsheet (preferably values that are specified).
So if possible, I'd like to specify the column names in VBA (Col1="Location") so that the macro is only applied to specific columns.
Example:
If I've specified, "Location" as a column header the macro should look for and A1 has "Location" as the header, then everything in A needs, "Location: " added to the front of it.
Basically, whatever the header is + ": ".
So this:
Location
A04B25
A05B89
B58C23
Would be this:
Location
Location: A04B25
Location: A05B89
Location: B58C23
This macro would need to cycle through each column and add that column header value to the values in the column IF it's on the list.
This is the code that I'm trying to use that isn't working:
Sub AppendHeader()
Dim i, LastCol
LastCol = Range("IV1").End(xlToLeft).Column
For i = 1 To LastCol
If UCase(Cells(1, i).Value) = "Local SKU" Then
Cells(1, i).EntireColumn.Append = UCase(Cells(1, i).Value) + ": "
End If
If UCase(Cells(1, i).Value) = "Supplier's SKU" Then
Cells(1, i).EntireColumn.Append = UCase(Cells(1, i).Value) + ": "
End If
Next
End Sub

Is this what you are trying?
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim preString As String
Dim lastRow As Long, LastCol As Long, i As Long, j As Long
Set ws = Sheets("Sheet1")
With ws
LastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
For i = 1 To LastCol
Select Case Trim(UCase(Cells(1, i).Value))
Case "LOCAL SKU", "SUPPLIER'S SKU"
lastRow = .Range(Split(Cells(, i).Address, "$")(1) & Rows.Count).End(xlUp).Row
preString = .Cells(1, i).Value & ": "
For j = 2 To lastRow
.Cells(j, i).Value = preString & .Cells(j, i).Value
Next j
End Select
Next i
End With
End Sub

There is a similar problem on SO, but I have come up with a different VBA solution. It will change the Number Format of the columns (except for the header row) based on that column's header.
To do this manually, you could select the "Custom" category for Format Cells and enter
"Location: "General;"Location: "#
This will make "Location: " show up in front of numbers, text, dates and such. Any formulas applied to these cells will take into account the prefix (Location:) but suppose you wanted to work with just the values. With this method, you can easily remove the formatting rather than creating a second subroutine to remove the prefix.
The code modifies Siddharth's -- Thank you, sir -- (I have not explicitly declared all the variables as he has, but that is best practice).
Sub Sample2()
Set ws = Sheets("Sheet1")
With ws
LastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
For i = 1 To LastCol
lastRow = .Range(Split(Cells(, i).Address, "$")(1) & Rows.Count).End(xlUp).Row
preString = .Cells(1, i).Value & ": "
Range(Cells(2, i), Cells(lastRow, i)).NumberFormat = _
Chr(34) & preString & Chr(34) & "General;" & _
Chr(34) & preString & Chr(34) & "#"
Next i
End With
End Sub

Related

Vba search and paste solution

i would like to come up with vba sub that searching value from one specified cell (job) across all sheets and then pastes rows but only with selected columns. If value not found any error message instead paste value.
I know it's bigger project but I'm fresh so try to my best.
As far i have solution for whole rows:
Sub TEST()
Dim tws As String
Dim l_row As String
Dim l_rowR As String
Dim job As String
Dim i As Integer
Set tws = ThisWorkbook.Sheets("Data")
tws.Range("A20") = "STATS:"
job = tws.Range("B5")
lastRow = Worksheets("Sheet1").Range("E" & Rows.Count).End(xlUp).Row
lastRowRpt = tws.Range("A" & Rows.Count).End(xlUp).Row
For i = 3 To lastRow
If Worksheets("Sheet1").Range("E" & i).Value = job And _
Worksheets("Sheet1").Range("D" & i).Value = "x2" Then
Worksheets("Sheet1").Rows(i).Copy
lastRowRpt = tws.Range("A" & Rows.Count).End(xlUp).Row
tws.Range("A" & lastRowRpt + 1).Select
tws.Paste
End If
Next i
End Sub

Different sheet pasting

I have written a code which gives me the errors (if any cell is non numeric) in a separate sheet called "Error_sheet".
But the output is a bit clumsy as it gives me non numeric cell address in a confusing fashion. Like the errors will not be pasted one after another. There will be some blanks in between if there are more than one non Numeric cells.
Sub Test()
Dim LastRow As Long, i As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For i = 2 To LastRow
If IsNumeric(Range("A" & i).Value) Then
Else
Sheets("Error").Range("A" & Row).Value = "Error in" & i & " row of ColumnNAme"
Row = Row + 1
End If
Next i
End Sub
It gives me output like shown below but can I get the output like Error in 7,14 rows of column name in a desired cell of "Error_sheet".
[![Output][1]][1]
[1]: https://i.stack.imgur.com/JqXwq.png
My understanding of what you've written is that you want something like this.
Option Explicit
Sub Test()
' Unqualified book/sheet below, means code will always run the isnumeric check on the cells of the active sheet. Is that what you want? '
Dim LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
Dim Index as long
Dim i As Long
Dim NonNumericRows() as string
Redim NonNumericRows(1 to lastrow)
For i = 2 To LastRow
If not(IsNumeric(Range("A" & i).Value)) Then
Index = index + 1
NonNumericRows(Index) = cstr(i)
End if
Next i
Redim preserve NonNumericRows(1 to index)
Sheets("Error").Range("A1").Value = "Error in row(s): " & strings.join(nonnumericrows,", ") & " of ColumnNAme"
End Sub
Hope it works or helps.
Like QHarr suggested, using Option Explicit is normally a good idea, and try not to use VBA operators as variables.
Also when working with more than 1 sheet, its best to define each in the code. I dont know what your first sheet is called, so please change the line: Set shSource = Sheets("Sheet1") to suit:
Option Explicit
Sub SubErrorSheet()
Dim lr As Long, i As Long
Dim shSource As Worksheet, shError As Worksheet
Set shSource = Sheets("Sheet1")
Set shError = Sheets("Error")
lr = shSource.Range("A" & Rows.count).End(xlUp).Row
For i = 2 To lr
If Not IsNumeric(shSource.Range("A" & i).Value) Then
shError.Range("A" & Rows.count).End(xlUp).Offset(1, 0).Value = "Error in row " & i & " of ColumnNAme"
End If
Next i
End Sub

Take out characters and put in a new column in Excel

Hi I'm a bit new to vba so I will try to explain my problem as far as possible.
I have a dataset in Excel in Column A, I have a lot of file names like this:
1. AB000**1234**45.tif
2. AB000**1235**45.tif
3. AB000**1236**45.tif
4. AB000**1237**45.tif
etc..
From this I want to take out all the strong characters and put in column C so it will look like this:
1. 1234
2. 1235
3. 1236
4. 1237
etc..
At the moment I have a code that looks like this:
Sub TakeOut
Dim str1 As String
Dim LR As Long
Dim cell As Range, RNG As Range
LR = Range("A" & Rows.Count).End(xlUp).Row
Set RNG = Range("A1:A" & LR)
For Each cell In RNG
L = Len(RNG)
If L > 0 Then
RNG = ...
End If
Next cell
Range("C:C").Columns.AutoFit
End Sub
I have tried to count left(5) and right(6) but don't know how to take out the 4 character that I want.
Hope you can help me with this.
If you want to take out the strong characters from the string. Try it below. It will take all the Bold Characters in a cell and place it in C column.
Hope you are looking for this?
Sub get_bold_content()
Dim lastrow, i, j, totlength As Long
lastrow = Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To lastrow
totlength = Len(Range("A" & i).Value)
For j = 1 To totlength
If Range("A" & i).Characters(j, 1).Font.Bold = True Then
outtext = outtext & Range("A" & i).Characters(j, 1).Text
End If
Next j
Range("C" & i).Value = outtext
outtext = ""
Next i
End Sub
Take a look at the Mid() Function link.
usage in your case:
Mid(cell.Value, 6, 4) 'First parameter is the string, 6 is the start character, 4 is length
The easiest way without looping would be something like this:
Sub TakeOut()
Dim rng As Range
Set rng = Range("A1", Range("A" & Rows.Count).End(xlUp))
rng.Offset(, 1) = Evaluate("IF(" & rng.Address & "="""","""",MID(" & rng.Address & ",6,4))")
End Sub

Runtime Error 5, invalid procedure or call argument

I am trying to assign Cell E8 in Sheet"Report" with an Index Match formula with a dynamic range. The range is from Sheet"Data"
I have found the last row (LR) and last column (lc).
The run time error occurs at the last line: Cell("E8").formula = "=...."
This is the code:
Sub report()
Dim LR As Long, lc As Long, first As Long, proxy As String
Sheets("Data").Select
'Finding the first filled cell by moving down from A1
first = Sheets("Data").Range("A1").End(xlDown).Row
'The first row has column headers: Name, ID number, etc... SO I assign it to the next row where the first data entry is
first = first + 1
LR = Sheets("Data").Range("A" & first).End(xlDown).Row
lc = Sheets("Data").Range("A" & first).End(xlToRight).Column
Sheets("Report").Select
proxy = "=IFERROR(INDEX(Data!$A$10:" & Cells(LR, lc).Address & ",MATCH(Report!$C$3,Data!$A$10:" & Cells(LR, 1).Address & ",0),MATCH(Report!$C8,Data!A$9:" & Cells(9, lc).Address & ",0)),'N/A')"
Cells("E8").Formula = proxy
End Sub
Sub report()
Dim LR As Long, lc As Long, first As Long, proxy As String
With Sheets("Data")
'Finding the first filled cell by moving down from A1
first = .Range("A1").End(xlDown).Row
'The first row has column headers: Name, ID number, etc... SO I assign it to the next row where the first data entry is
first = first + 1
LR = .Range("A" & Rows.Count).End(xlUp).Row
lc = .Range("A" & first - 1).End(xlToRight).Column
End With
proxy = "=IFERROR(INDEX(Data!$A$10:" & Cells(LR, lc).Address & ",MATCH(Report!$C$3,Data!$A$10:" & Cells(LR, 1).Address & ",0),MATCH(Report!$C8,Data!A$9:" & Cells(9, lc).Address & ",0)),""N/A"")"
Sheets("Report").Range("E8").Formula = proxy
End Sub
You are using single quotes to wrap 'N/A'. You need double quotes and because they are quotes within a quoted string, you need to double them up. Additionally, the Range.Cells property does not accept the same style of cell address references that a Range object does.
proxy = "=IFERROR(INDEX(Data!$A$10:" & Cells(LR, lc).Address & _
",MATCH(Report!$C$3,Data!$A$10:" & Cells(LR, 1).Address & _
",0),MATCH(Report!$C8,Data!A$9:" & Cells(9, lc).Address & _
",0)),""N/A"")"
Sheets("Report").Select
Range("E8").Formula = proxy
Here is a quick rewrite that gets away from using Worksheet.Select¹ method and the implicit ActiveSheet property.
Sub report()
Dim lr As Long, lc As Long, first As Long, proxy As String
With Worksheets("Data")
'Finding the first filled cell by moving down from A1
first = .Range("A1").End(xlDown).Row
'The first row has column headers: Name, ID number, etc... SO I assign it to the next row where the first data entry is
first = first + 1
lr = .Range("A" & first).End(xlDown).Row
lc = .Range("A" & first).End(xlToRight).Column
End With
proxy = "=IFERROR(INDEX(Data!$A$10:" & Cells(lr, lc).Address & _
",MATCH(Report!$C$3,Data!$A$10:" & Cells(lr, 1).Address & _
",0),MATCH(Report!$C8,Data!A$9:" & Cells(9, lc).Address & _
",0)),""NA"")"
With Worksheets("Report")
.Range("E8").Formula = proxy
'alternate with .Cells as one of these
'.Cells(8, "E").Formula = proxy
'.Cells(8, 5).Formula = proxy
End With
End Sub
.¹ See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals.

Sum of a column

I want to calculate Sum of different columns in a worksheet and fill it in another worksheet.
LastrowA = Weight.Cells(Weight.Rows.Count, "A").End(xlUp).Row
Set Rng = Weight.Range("A2" & LastrowA)
Weight.Activate
Summ= WorksheetFunction.Sum(Rng) ' Doesn't work
Summary.Cells(1, 1).Value=Summ
Summary.Cells(1, 1).Value = Application.Sum(Rng) ' Doesn't Work
The two Sheets are Weight and Summary. I have tried above two ways and both give me an answer of Zero. I want to continue doing it for all my columns . Please advice. Thank you.
This sub will sum data in Sheet 1 Columns A to C and put results in Sheet2
You can use this sub and just change column letters and output cells.
Hope this helps
Sub SumRange()
Dim wb as Workbook
Set wb = Thisworkbook
Dim ws as worksheet
Set Weight = wb.Sheets("Weight")
LastRow1 = Weight.Range("A" & Rows.Count).End(xlUp).Row
Set Rng = Weight.Range("A2:A" & "" & LastRow1 & "")
Col1Sum = WorksheetFunction.Sum(Rng)
LastRow1 = Weight.Range("B" & Rows.Count).End(xlUp).Row
Set Rng = Weight.Range("B2:B" & "" & LastRow1 & "")
Col2Sum = WorksheetFunction.Sum(Rng)
LastRow1 = Weight.Range("C" & Rows.Count).End(xlUp).Row
Set Rng = Weight.Range("C2:C" & "" & LastRow1 & "")
Col3Sum = WorksheetFunction.Sum(Rng)
ThisWorkbook.Sheets("Sheet2").Cells(2, 2).Value = Col1Sum
ThisWorkbook.Sheets("Sheet2").Cells(3, 2).Value = Col2Sum
ThisWorkbook.Sheets("Sheet2").Cells(4, 2).Value = Col3Sum
End Sub
first of all, i have no excel here, so i cant try by myself what I'm thinking.
but i think you use the Range-Method the wrong way.. it should look like this:
Set Rng = Weight.Range("A2" , Cells( LastrowA , "A") )
so there is a "," between the arguments instead of a "&" an there is a second Cell instead of a row-number.
Hope that helps