Split data into multiple sheets based on column - excel

#Modifying Question for better understanding and how do i want the result is.
Wizhi answer almost matched for my question !! But need some more
changes in his answer because which code is not working for me !! And
no need to work based on GCN Date as he answered. The split work
done based on Destination Pincode .
Please help someone help me to Macro Code for Split data into multiple sheet within an excel workbook based on a table format. Below is the explanation of how i have done as per my knowledge and what is my expectation is !!
"Here is the workbooks what i have Done"
Please download the Macro_Folder and Unzip it in you "C" Drive.
Open Macro Workbook and Press Button to run macro.
If it asked for updating formulas as shown in below picture please select "Don't Update" to continue macro.
My Macro workbook view :
I Have done button option to Run the split macro in separate excel workbook.
Where the files Located
When self open and run Macro from Macro Workbook it automatically opens my XD MIS Report and start formatting and split the date into multiple sheets.
View of XD MIS is "Master Data" which is having overall raw data.
Here is the view after self Run Macro fro split Master data.
Code that i Used For Split Data into Multiple Sheet:
Sub Spli_Data()
Dim wb As Workbook
Dim myfilename As String
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
myfilename = "C:\Macro\XD MIS Report.xlsx"
Set wb = Workbooks.Open(myfilename)
Cells.Select
Selection.EntireColumn.Hidden = False
Selection.EntireRow.Hidden = False
Columns("B:F").Select
Range("B2").Activate
Selection.Delete Shift:=xlToLeft
Columns("D:E").Select
Range("D2").Activate
Selection.Delete Shift:=xlToLeft
Columns("H:H").Select
Range("H2").Activate
Selection.Delete Shift:=xlToLeft
Columns("K:L").Select
Range("K2").Activate
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Delete Shift:=xlToLeft
Columns("D:D").Select
Range("D2").Activate
Selection.Cut
Selection.End(xlToRight).Select
Columns("K:K").Select
Range("K2").Activate
Selection.Insert Shift:=xlToRight
Selection.End(xlUp).Select
Range("K1").Select
ActiveCell.FormulaR1C1 = "Remarks"
Columns("J:J").Select
Selection.Copy
Columns("K:K").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Columns("H:H").Select
Selection.Insert Shift:=xlToRight
Range("H1").Select
ActiveCell.FormulaR1C1 = "Packing Type"
Range("H1").Select
Selection.End(xlToLeft).Select
Cells.Select
Selection.FormatConditions.Delete
Columns("B:B").Select
Selection.Copy
Columns("A:A").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Range("A2").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=COUNTIF(R[-1]C[6]:RC[6],RC[6])"
Range("A2").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(R1C7:RC[6],RC[6])"
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.FillDown
Selection.End(xlUp).Select
Columns("A:A").Select
Range("A2").Activate
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A2").Select
Application.CutCopyMode = False
Range("A1:L3100").Select
Range("A2").Activate
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection
.VerticalAlignment = xlBottom
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
End With
With Selection
.VerticalAlignment = xlCenter
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
End With
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlCenter
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
End With
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
End With
With Selection.Font
.Name = "Calibri"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
End With
With Selection.Font
.Name = "Calibri Light"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
.ThemeFont = xlThemeFontMajor
End With
Range("A2").Select
Application.ScreenUpdating = False
vcol = Application.InputBox(prompt:="Which column would you like to filter by?", title:="Filter column", Default:="3", Type:=1)
Set ws = ActiveSheet
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1"
titlerow = ws.Range(title).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
For i = 2 To lr
On Error Resume Next
If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
End If
Next
myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
Next
ws.AutoFilterMode = False
ws.Activate
Application.ScreenUpdating = True
End Sub
Result Of Split Data What i have right now:
Destination 1
Destination 2
Now Let's Clear About My Requirement:
I have done macro for format and Split Data into multiple Sheet,But this the not exact format result which i'm looking for.
The split should be done in same method but for result format should be like below formats based on macro code.
The split data should be in Multiple sheets of within an Excel Workbook . Not split to multiple workbooks !!
Write a macro for split Data in this format for all Destination Pincode:
This how i'm expecting final result through macro code
Expected Format of #Destination 1 Sample After Split done
#Destination 1 Sample
This is an examples of what i'm looking for. The same have to done
for all destination which is in Master Data
Hope !! now my question is clear for better understanding and easy to answer.

Updated code:
#Mark Balhoff, Thanks for your valuable input, I always like to learn and get feedback to improve myself :). I have used your input in the code and also extended it a bit.
This code is using dictionary so you need to activate "Microsoft Scripting Runtime"
"Tools" -> "References" -> "Microsoft Scripting Runtime" to make dictionary work
User process to split Master Data:
I assume that the user will split this data in the picture:
Pressing the button, it will choose column 7.
(My opinion is that this part with InputBox etc... is unnecessary as you always want to filter by column 7 regardless, so I feel it confused the end user)
Is quite unclear from what "raw data" you start with as new pictures/data have appeared in the updated question. I have assumed that the data that we should split looks like this, as it was stated first
Output of the first unique Destination Pincode:
Output of the second unique Destination Pincode:
Code:
Option Explicit
Sub Split()
Dim lr As Long
Dim lc As Long
Dim ws As Worksheet
Dim ws_new As Worksheet
Dim DestPincode As Range
Dim DestPincodeCol As Long
Dim vcol As Long
Dim vcol_value As String
Dim vcol_name As String
Dim vcol_prompt As String
Dim i As Integer
Dim DestPincode_ws_new As Range
Dim DestPincodeCol_ws_new As Long
Dim DestPincodeRow_ws_new As Long
Application.ScreenUpdating = False
'##### SETTINGS #####
Set ws = ActiveWorkbook.Worksheets("Master_Data") 'Set master data sheet
Set DestPincode = ws.Range(ws.Cells(1, 1), ws.Cells(1, ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column)).Find(What:="Destination Pincode", LookIn:=xlValues, LookAt:=xlWhole) 'Set name to search after, i.e. Destination
'####################
lc = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column 'Find last column in Master Data
DestPincodeCol = DestPincode.Column 'Get column number for Destination Pincode
lr = ws.Cells(ws.Rows.Count, DestPincodeCol).End(xlUp).Row 'Get last row
'This macro splits data into multiple worksheets based on the variables on a column found in Excel.
'An InputBox asks you which columns you'd like to filter by, and it just creates these worksheets.
'##### Filter based on InputBox #####
vcol = Application.InputBox(prompt:="Which column would you like to filter by?", title:="Filter column", Default:="7", Type:=1)
If vcol <> 7 Then Exit Sub
'##### Get all the uniqe "Destination Pincodes" #####
' You need to activate "Tools" -> "References" -> "Microsoft Scripting Runtime" to make dictionary work
Dim DestPincodeData()
Dim UniqueDestPincodeData As Object
Dim DestPinRow As Long
Set UniqueDestPincodeData = CreateObject("Scripting.Dictionary")
DestPincodeData = Application.Transpose(ws.Range(ws.Cells(1, DestPincodeCol), ws.Cells(ws.Cells(Rows.Count, DestPincodeCol).End(xlUp).Row, DestPincodeCol))) 'Get all the Destination Pincode values
For DestPinRow = 2 To UBound(DestPincodeData, 1) 'Start from row 2 (to skip header) and add unique values to the dictionary
UniqueDestPincodeData(DestPincodeData(DestPinRow)) = 1 'Add value to dictionary
Next
'##### Loop through all the unqie Destination Pincodes and add to seperate workbooks #####
Dim new_wb As Workbook
Set new_wb = Application.Workbooks.Add 'Add new workbook
'Set new_wb = ActiveWorkbook
Dim DestPincodeName As Variant
Dim MyRangeFilter As Range
Set MyRangeFilter = ws.Range(ws.Cells(1, 1), ws.Cells(lr, lc)) 'Filter range 'Set filter range
For Each DestPincodeName In UniqueDestPincodeData.Keys 'Filter through all the unique names in dictionary "UniqueDestPincodeData"
'Debug.Print "Destination Pincode: " & DestPincodeName 'Print current unique Destination Pincode name
'Filter the data based on "Destination Pincode" and Column from InputBox
With MyRangeFilter
.AutoFilter Field:=DestPincodeCol, Criteria1:=DestPincodeName, Operator:=xlFilterValues 'Filter on Destination Pincode
End With
'##### Create new workbook for the filtered data #####
'To add to new worksheet:
Sheets.Add(After:=Sheets(Sheets.Count)).Name = DestPincodeName
Set ws_new = new_wb.Worksheets(DestPincodeName)
'##### Create template in the new workbook #####
'Building template output, row by row
ws_new.Range("A1:A7").Value = WorksheetFunction.Transpose( _
Array("*******", "TRIP NO", "TRIP DATE/TIME", "TRUCKTYPE (OWN/ATT/ADHOC)", "SEAL #", "SUPERVISOR NAME", "REMARK"))
ws_new.Range("H2:H6").Value = WorksheetFunction.Transpose( _
Array("VEHICLE NO", "VEHICLE CAPACITY", "DRIVER NAME", "DRIVER NO", "VENDOR NAME"))
Dim Top_Area_Cell_Format As Range
Set Top_Area_Cell_Format = ws_new.Range("A1:L1,A7:L7,A2:D2,E2:G2,H2:I2,J2:L2," _
& "A3:D3,E3:G3,H3:I3,J3:L3,A4:D4,E4:G4,H4:I4," _
& "J4:L4,A5:D5,E5:G5,H5:I5,J5:L5,A6:D6,E6:G6,H6:I6,J6:L6")
Application.DisplayAlerts = False
Top_Area_Cell_Format.Merge 'Merge cells
Top_Area_Cell_Format.HorizontalAlignment = xlLeft 'Make title in center
Top_Area_Cell_Format.Borders.LineStyle = xlContinuous 'Add border lines
Top_Area_Cell_Format.Font.Bold = True 'Add Bold text
ws_new.Range("A1:L1").HorizontalAlignment = xlCenter 'Make title in center
Application.DisplayAlerts = True
'##### Paste filtered data from Master_Data sheet #####
ws.Range(ws.Cells(1, 1), ws.Cells(lr, lc)).SpecialCells(xlCellTypeVisible).HorizontalAlignment = xlCenter 'Make text in center
ws.Range(ws.Cells(1, 1), ws.Cells(lr, lc)).SpecialCells(xlCellTypeVisible).EntireRow.Copy 'Copy entire row from filtered data
ws_new.Cells(8, "A").PasteSpecial xlPasteAll 'Paste all values including formats
Set DestPincode_ws_new = ws_new.Range(ws_new.Cells(8, 1), ws_new.Cells(1, ws_new.Cells(8, ws_new.Columns.Count).End(xlToLeft).Column)).Find(What:="Destination Pincode", LookIn:=xlValues, LookAt:=xlWhole) 'Set name to search after, i.e. Destination
DestPincodeCol_ws_new = DestPincode_ws_new.Column
DestPincodeRow_ws_new = ws_new.Cells(ws_new.Rows.Count, DestPincodeCol_ws_new).End(xlUp).Row
'Add total
ws_new.Cells(DestPincodeRow_ws_new + 1, "A").Value = "TOTAL"
ws_new.Range(ws_new.Cells(DestPincodeRow_ws_new + 1, "A"), ws_new.Cells(DestPincodeRow_ws_new + 1, "G")).Merge 'Merge cells
ws_new.Range(ws_new.Cells(DestPincodeRow_ws_new + 1, "A"), ws_new.Cells(DestPincodeRow_ws_new + 1, "G")).HorizontalAlignment = xlCenter 'Make text in center
ws_new.Range(ws_new.Cells(DestPincodeRow_ws_new + 1, "A"), ws_new.Cells(DestPincodeRow_ws_new + 1, "G")).Borders.LineStyle = xlContinuous 'Add border lines
ws_new.Range(ws_new.Cells(DestPincodeRow_ws_new + 1, "A"), ws_new.Cells(DestPincodeRow_ws_new + 1, "G")).Font.Bold = True 'Add Bold text
'Add total values
ws_new.Range(ws_new.Cells(DestPincodeRow_ws_new + 1, "I"), ws_new.Cells(DestPincodeRow_ws_new + 1, "I")).Formula = "=SUM(I9:I" & DestPincodeRow_ws_new & ")" 'Add sum for "No. of cartons"
ws_new.Range(ws_new.Cells(DestPincodeRow_ws_new + 1, "J"), ws_new.Cells(DestPincodeRow_ws_new + 1, "J")).Formula = "=SUM(J9:J" & DestPincodeRow_ws_new & ")" 'Add sum for "Actual weights"
ws_new.Range(ws_new.Cells(DestPincodeRow_ws_new + 1, "H"), ws_new.Cells(DestPincodeRow_ws_new + 1, "L")).Borders.LineStyle = xlContinuous 'Add border lines
ws_new.Range(ws_new.Cells(DestPincodeRow_ws_new + 1, "H"), ws_new.Cells(DestPincodeRow_ws_new + 1, "L")).Font.Bold = True 'Add Bold text
'##### Add sign boxes #####
Dim Bottom_Area_Cell_Text_Rng As String
Dim Bottom_Area_Cell_Format As String
Dim Bottom_Area_Cell_Format_rng As Range
Bottom_Area_Cell_Text_Rng = "B" & DestPincodeRow_ws_new + 2 & ":H" & DestPincodeRow_ws_new + 2
ws_new.Range(Bottom_Area_Cell_Text_Rng).Value = Array("Driver Signature", "", "Incharge Signature", "", "Security Signature", "", "REMARK")
Bottom_Area_Cell_Format = "A" & DestPincodeRow_ws_new + 2 & ":A" & DestPincodeRow_ws_new + 4 & "," _
& "B" & DestPincodeRow_ws_new + 2 & ":C" & DestPincodeRow_ws_new + 4 & "," _
& "D" & DestPincodeRow_ws_new + 2 & ":E" & DestPincodeRow_ws_new + 4 & "," _
& "F" & DestPincodeRow_ws_new + 2 & ":G" & DestPincodeRow_ws_new + 4 & "," _
& "H" & DestPincodeRow_ws_new + 2 & ":L" & DestPincodeRow_ws_new + 4
Set Bottom_Area_Cell_Format_rng = ws_new.Range(Bottom_Area_Cell_Format)
Application.DisplayAlerts = False
Bottom_Area_Cell_Format_rng.Merge 'Merge cells
Bottom_Area_Cell_Format_rng.HorizontalAlignment = xlLeft 'Make title in center
Bottom_Area_Cell_Format_rng.Borders.LineStyle = xlContinuous 'Add border lines
Bottom_Area_Cell_Format_rng.VerticalAlignment = xlTop 'Alignment of text
Bottom_Area_Cell_Format_rng.Font.Bold = True 'Add Bold text
Application.DisplayAlerts = True
'Adjust Column width
ws_new.Columns("A:L").Select
Selection.EntireColumn.AutoFit
Set ws_new = Nothing 'Reset worksheet value
Next
Application.DisplayAlerts = False
new_wb.Worksheets(1).Delete
Application.DisplayAlerts = True
On Error Resume Next
Sheet1.ShowAllData 'remove filter
On Error GoTo 0
ws.AutoFilterMode = False
Application.ScreenUpdating = True
End Sub
Link to workbook:
https://www.dropbox.com/s/86wlv99y6wylpn8/split%20data.xlsm?dl=0

I'm not sure If I've understand properly, but it looks like you want to split your data depending on the value of PINCODE column.
Besides, your question is too broad right now, you should focus more.
So, as example, I understand you would select all rows containing PINCODE=PUZHAL, and copy all of them into a different workbook.
And you want this for each unique PINCODE.
I made a fake dataset coloring rows, and I split the data into new workbooks. You'll need to adapt this to paste the data into existing workbooks (or new worksheets of same workbook, whatever)
My data is like this:
My code:
Sub TEST()
Application.ScreenUpdating = False
Dim MyDict As Object
Dim i As Long
Dim MyKey As Variant
Dim LR As Long
Dim WB As Workbook
Dim MyRows As Variant
LR = Range("G" & Rows.Count).End(xlUp).Row
Set MyDict = CreateObject("Scripting.Dictionary")
For i = 2 To LR Step 1
If MyDict.Exists(Range("G" & i).Value) = False Then
'we create the PINCODE in Dictionary and assign row number
MyDict.Add Range("G" & i).Value, i
Else
'PINCODE already in Dictionary, we add the new row number
MyDict(Range("G" & i).Value) = MyDict(Range("G" & i).Value) & "|" & i
End If
Next i
'now Dictionary holds all pincodes and all row numbers for each pincode.
'we create a workbook for each PINCODE, but you can adapt this to open a exact workbook depending on PINCODE
'I'm copying the rows starting at row 1, but you can adapt this to your model for sure
For Each MyKey In MyDict.Keys
Set WB = Application.Workbooks.Add
LR = 1 'change this to starting row
MyRows = Split(MyDict(MyKey), "|") 'we create array of rows numbers
For i = LBound(MyRows) To UBound(MyRows) Step 1
'we copy range A:L from that row into destiny workbook
ThisWorkbook.ActiveSheet.Range("A" & MyRows(i) & ":L" & MyRows(i)).Copy WB.ActiveSheet.Range("A" & LR & ":L" & LR)
LR = LR + 1 'we increase LR so next data will be pasted into next row
Next i
Erase MyRows
Set WB = Nothing
DoEvents
Next MyKey
MyDict.RemoveAll
Set MyDict = Nothing
Application.ScreenUpdating = True
End Sub
And this is how i get all my data splitted into different files depending on PINCODE.

I suggest You create a Pivot Table.
By that Pivot table you create a code to extract data on a pivotable base on a list and transfer that to the formatted workbook you created and make a loop until the last Destination Pincode. I also use Excel VBA Form to Trigger this. I can make you one if you post your Excel here.

I've created a macro that transfers the selected value from the dropdown list to the sheet with the same name as the value. I recommend that you review it.
Source : Split data into multiple sheets

Related

Excel VBA sheet name list with maxing colors

I am trying to write a VBA function where I produce a new sheet, give a lists of all the sheet names in the workbook and match the cell color of the sheet name, with the tab color of the sheet name. The pseudocode will look something like this:
Create a new sheet
Loop through all sheets in the workbook
Write down the sheet name in the created sheet
Retrieve the sheet ThemeColor (e.g. xlThemeColorLight2)
Retrieve the sheet TintAndShade (e.g. 0.799981688894314
Set the cell in which the name of the sheet is to the correct ThemeColor and TintAndShade
End
Is there a way in which this is possible?
Sub SheetList()
Dim ws As Worksheet
Dim x As Integer
x = 1
Sheets.Add
sheet_name = InputBox("Please enter a sheet name")
ActiveSheet.Name = sheet_name # Create a new sheet name
For Each ws In Worksheets
Sheets(sheet_name).Cells(x, 1) = ws.Name # Set cell value to sheet name
Dim theme_color As String
Dim tint_and_shade As Single
theme_color = ... # Attain sheet ThemeColor of current ws here
tint_and_shade = ... # Attain sheet TintAndShade of current ws here
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = theme_color # Set current cell to theme_color
.TintAndShade = tint_and_shade # Set current cell to tint_and_shade
.PatternTintAndShade = 0
End With
x = x + 1
Next ws
You can use ws.Tab.ThemeColor and ws.Tab.TintAndShade to retrieve those values.
I updated your code so that you can use the wsNewvariable to refer to the new worksheet.
Furthermore I am checking that only color codes of the other worksheets are checked.
Sub SheetList()
Dim wsNew As Worksheet
With ThisWorkbook.Worksheets
Set wsNew = .Add(.Item(1))
End With
Dim sheet_name
sheet_name = InputBox("Please enter a sheet name")
wsNew.Name = sheet_name ' Create a new sheet name
Dim ws As Worksheet, c As Range, x As Long
For Each ws In Worksheets
If Not ws Is wsNew Then
x = x + 1
Set c = wsNew.Cells(x, 1)
c.Value = ws.Name ' Set cell value to sheet name
Dim theme_color As Single
Dim tint_and_shade As Single
theme_color = ws.Tab.ThemeColor ' Attain sheet ThemeColor of current ws here
tint_and_shade = ws.Tab.TintAndShade ' Attain sheet TintAndShade of current ws here
With c.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
If theme_color > 0 Then
.ThemeColor = theme_color ' Set current cell to theme_color
End If
.TintAndShade = tint_and_shade ' Set current cell to tint_and_shade
.PatternTintAndShade = 0
End With
End If
Next ws
End Sub
Thanks for your help Ike. I made a full piece of code to get a sheet overview page. It is not the most elegant piece of code, but here it is:
Sub SheetOverview()
'
' SheetOverview
'
Dim ws As Worksheet
Dim x As Integer
Dim c As Range
x = 1
' Add new sheet, ask user for sheet name
Sheets.Add
ActiveWindow.DisplayGridlines = False
sheet_name = InputBox("Please enter a sheet name")
ActiveSheet.Name = sheet_name
' Loop to obtain all sheet names
For Each ws In Worksheets
Set c = Sheets(sheet_name).Cells(x, 1)
c.Value = ws.Name
Dim theme_color As Single
Dim tint_and_shade As Single
theme_color = ws.Tab.ThemeColor ' Attain sheet ThemeColor of current ws here
tint_and_shade = ws.Tab.TintAndShade ' Attain sheet TintAndShade of current ws here
With c.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
If theme_color > 0 Then
.ThemeColor = theme_color ' Set current cell to theme_color
End If
.TintAndShade = tint_and_shade ' Set current cell to tint_and_shade
.PatternTintAndShade = 0
End With
x = x + 1
Next ws
' Cut selection
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Cut
Range("A6").Select
ActiveSheet.Paste
' Enter Sheets and Description and format
Range("A5").Select
ActiveCell.FormulaR1C1 = "Sheets"
Range("B5").Select
ActiveCell.FormulaR1C1 = "Description"
Range("A5:B5").Select
Selection.Font.Bold = True
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
' Format title
Range("A4").Select
Selection.End(xlUp).Select
Selection.Font.Bold = True
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.149998474074526
.PatternTintAndShade = 0
End With
Selection.Font.Size = 14
Range("A2").Select
ActiveCell.FormulaR1C1 = "Author:"
Range("B2").Select
ActiveCell.FormulaR1C1 = "[Enter author here]"
Selection.Font.Italic = True
Range("A3").Select
ActiveCell.FormulaR1C1 = "Date:"
Range("B3").Select
ActiveCell.FormulaR1C1 = "=TODAY()"
Selection.Copy
Range("B3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Rows("4:4").Select
Selection.Insert Shift:=xlDown
Selection.Borders(xlLeft).LineStyle = xlNone
Selection.Borders(xlRight).LineStyle = xlNone
Selection.Borders(xlTop).LineStyle = xlNone
Selection.Borders(xlBottom).LineStyle = xlNone
Range("A4").Select
ActiveCell.FormulaR1C1 = "Time:"
Range("B4").Select
ActiveCell.FormulaR1C1 = "=NOW()-TODAY()"
Range("B4").Select
Selection.Copy
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "[$-x-systime]h:mm:ss AM/PM"
Columns("A:B").Select
Range("A5").Activate
Selection.Columns.AutoFit
Range("B1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.149998474074526
.PatternTintAndShade = 0
End With
Columns("B:B").ColumnWidth = 52.11
Range("B3:B4").Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A1").Select
End Sub
Insert Sheet List
Sub InsertSheetList()
' Define constants.
Const Title As String = "Insert Sheet List"
Const FIRST_CELL As String = "A1"
Dim Headers() As Variant
Headers = VBA.Array("Index", "Color", "Name", "Type")
' Attempt to reference the workbook.
Dim wb As Workbook: Set wb = ActiveWorkbook
If wb Is Nothing Then
MsgBox "No visible workbooks open.", vbExclamation, Title
Exit Sub
End If
' Input sheet name.
Dim SheetName As String
SheetName = InputBox("Please enter a sheet name", Title)
If Len(SheetName) = 0 Then
MsgBox "Dialog canceled.", vbExclamation
Exit Sub
End If
' Add a worksheet to be the first and reference it.
wb.Sheets.Add Before:=wb.Sheets(1)
Dim dws As Worksheet: Set dws = wb.Sheets(1)
' Attempt to rename the worksheet.
Dim ErrNum As Long
On Error Resume Next
dws.Name = SheetName
ErrNum = Err.Number
On Error GoTo 0
If ErrNum <> 0 Then
Application.DisplayAlerts = False
dws.Delete
Application.DisplayAlerts = True
MsgBox "Couldn't use '" & SheetName & "' for a sheet name.", _
vbExclamation, Title
Exit Sub
End If
' Calcuate the number of columns (headers).
Dim ColumnsCount As Long: ColumnsCount = UBound(Headers) + 1
' Write the headers.
Dim drg As Range
Set drg = dws.Range(FIRST_CELL).Resize(, ColumnsCount)
drg.Value = Headers
' Write the list.
Dim sh As Object
Dim r As Long
For Each sh In wb.Sheets
r = r + 1
If r > 1 Then
Set drg = drg.Offset(1)
drg.Cells(1).Value = sh.Index
drg.Cells(2).Interior.Color = sh.Tab.Color
drg.Cells(3).Value = sh.Name
drg.Cells(4).Value = TypeName(sh)
End If
Next sh
' Autofit.
dws.Columns(1).Resize(, ColumnsCount).AutoFit
' Inform.
MsgBox "Sheet list created.", vbInformation, Title
End Sub

Pasting as link errors out

I wrote a code with a loop that copies a special cell in a source workbook and then opens another workbook and pastes a copied number to a special cell, and after seven times I get this error:
this is my code:
ActiveSheet.Paste Link:=True
I don't understand why it happens.
Sub Shadow()
ActiveSheet.Range("$A$1:$I$9627").AutoFilter Field:=4, Criteria1:="basic"
' Copy filtered worksheet
Number = Application.WorksheetFunction.Subtotal(3, Range("A1:A500000"))
ActiveSheet.Range("$A$1:$I$9627").SpecialCells(xlCellTypeVisible).Copy
' Addition of new sheet
Sheets.Add
ActiveSheet.Paste
' Calculating number of rows
finalrow = Cells(Rows.Count, 1).End(xlUp).Row
' A loop for copying row by row number and date then opening shadowgraph for pasting copied data
Dim i1 As Integer
For i1 = 2 To finalrow
ActiveSheet.Cells(i1, 1).Copy
Workbooks.Open Filename:="E:\Attachment\PCI\Clutch disc\FLEXIBALE (RO)\Shadowgraph.xlsm"
Windows("Shadowgraph.xlsm").Activate
Range("AW5").Select
ActiveSheet.Paste Link:=True
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Windows("ball99.xlsm").Activate
' Representing relative name for saving documents
Dim Name1 As String
Name1 = ActiveSheet.Cells(i1, 2) & "Shadowgraph"
ActiveSheet.Cells(i1, 2).Copy
Windows("Shadowgraph.xlsm").Activate
Range("E32").Select
ActiveSheet.Paste Link:=True
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
' Set work directory
ChDir "E:\Attachment\PCI\Clutch disc\FLEXIBALE (RO)"
' Set saving address
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"E:\Attachment\PCI\Clutch disc\FLEXIBALE (RO)\" & _
Name1, Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Windows("Shadowgraph.xlsm").Activate
' Closing opened datasheets
Windows("Shadowgraph.xlsm").Close (False)
Next i1
Windows("ball99.xlsm").Activate
' Closing every sheets except main workbook 01
Dim ws1 As Worksheet
For Each ws1 In ActiveWorkbook.Worksheets
If ws1.Name <> "01" Then ws1.Visible = xlSheetHidden
Next ws1
' Clearing all fiters
ActiveSheet.ShowAllData
End Sub

pivot table creation on different sheets fails on second sheet

I am new in VBA programming and this is one my first codes i am writing.
Purpose of code: I'd like to take data on Invoices sheet and take it apart to different sheets based on the last column. Then on each sheet create a pivot table for the data.
The code is quite long - i am sure there are quite a lot of unnecessary steps in it but it is 90% ok.
The frist sheet is created perfectly. The first pivot is also created. Then the second sheet is also created.
Problem: The macro runs on an error when it tries to create the pivot table for the second sheet.
Error message: Run-time error'5': Invalid Procedure call or argument
Does anyone have an idea why my macro fails on the second sheet? Thank You for your help!
Pleaase see the code below. The problem occurs after the comment of creating a pivot table
Sub copypaste()
Application.ScreenUpdating = False
'Declarations
Dim ws As Worksheet
Dim wb As Workbook
Dim cell As Range
Dim rng As Range
Dim rng1 As Range
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim LastRow As Long
Dim LastRow2 As Long
Dim Counter As Integer
Set wb = ActiveWorkbook
Set ws2 = wb.Sheets("Invoices")
Counter = 0
Debug.Print Counter
'get the number of rows in the invoices sheet
LastRow = ws2.Range("A1", ws2.Range("A1").End(xlDown)).Rows.Count
'plus invoice type and sum column creation
ws2.Select
Columns(6).Select
Range("F:F").Insert
Cells(1, 6) = "Invoice type"
Range("F2:F" & LastRow).Formula = "=LEFT(RC[1],4)"
Selection.Columns.AutoFit
Columns(19).Select
Range("S:S").Insert
Cells(1, 19) = "Sum"
Range("S2:S" & LastRow).Formula = "=SUM(RC[-8]:RC[-1])"
Selection.Style = "Comma"
Selection.NumberFormat = _
"_-* #,##0.0 _F_t_-;-* #,##0.0 _F_t_-;_-* ""-""?? _F_t_-;_-#_-"
Selection.NumberFormat = _
"_-* #,##0 _F_t_-;-* #,##0 _F_t_-;_-* ""-""?? _F_t_-;_-#_-"
Selection.Columns.AutoFit
'sorbarendezés debtor name és invoice no. szerint
ws2.Sort.SortFields.Clear
Range("A1:R" & LastRow).Sort Key1:=Range("E1"), Header:=xlYes, Key2:=Range("G1")
'list creation as a basis for filtering and taking apart the data
wb.Activate
ws2.Select
Range("A1").Select
Selection.End(xlToRight).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Set ws3 = Sheets.Add
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveSheet.Range(Selection, Selection.End(xlDown)).RemoveDuplicates Columns:=1, Header:= _
xlYes
Range("A2").Select
Set rng1 = Range(Selection, Selection.End(xlDown))
ws3.Select
ws3.Name = "kódolás"
Set ws = wb.Sheets("kódolás")
wb.Activate
ws.Select
'go through the earlier created list and take apart the data related to each item of the list to separate sheets
For Each cell In rng1
Counter = Counter + 1
Debug.Print Counter
'filtered data copy
ws2.Select
Range("A1").Select
ws2.Range("$A$1:$W$198162").AutoFilter Field:=20, Criteria1:=cell
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
'new sheet creation
With wb
.Sheets.Add after:=.Sheets(.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = cell.Value
If Err.Number = 1004 Then
Debug.Print cell.Value & " already used as a sheet name"
End If
On Error GoTo 0
End With
'filtered data paste
ActiveSheet.Paste
ActiveCell.Rows("1:1").EntireRow.Select
Application.CutCopyMode = False
'go back to A1
Range("A1").Select
'Creation of pivot table
LastRow2 = ActiveSheet.Range("A1", ActiveSheet.Range("A1").End(xlDown)).Rows.Count
ActiveCell.Range("A1:T" & LastRow2).Select
Debug.Print Counter
Debug.Print LastRow2
Debug.Print ActiveSheet.Name & "!" & "R1C1:R" & LastRow2 & "C19"
Debug.Print ActiveSheet.Name & "!" & "R1C23"
Debug.Print "PivotTable" & Counter
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
ActiveSheet.Name & "!" & "R1C1:R" & LastRow2 & "C19", Version:=6).CreatePivotTable TableDestination:= _
ActiveSheet.Name & "!" & "R1C23", TableName:="PivotTable" & Counter, DefaultVersion:=6
ActiveSheet.Select
Cells(1, 27).Select
With ActiveSheet.PivotTables("PivotTable" & Counter)
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
End With
With ActiveSheet.PivotTables("PivotTable" & Counter).PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PivotTable" & Counter).RepeatAllLabels xlRepeatLabels
With ActiveSheet.PivotTables("PivotTable" & Counter).PivotFields("Debtor name")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable" & Counter).PivotFields("invoice type")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("PivotTable" & Counter).AddDataField ActiveSheet.PivotTables( _
"PivotTable" & Counter).PivotFields("SUM"), "Sum of SUM", xlSum
'take out filter and go back to A1
ws2.Select
Application.CutCopyMode = False
Range("A1").Select
ws2.AutoFilter.Sort.SortFields.Clear
ActiveSheet.ShowAllData
Next cell
End Sub

UPDATE - see Edit Summary: New to VBA: Code is slow and goes into Excel "Not Responding" before completing

This code takes raw data and drops it into a report template where it is transformed using if then statements and conditional formatting. Data is downloaded from an online source. The imported file is moved into the workbook. The user then runs this macro to merge the imported file into the report template.
Before adding the ActiveWorkbook.Save line, this code would only run about half the time. Now it runs consistently, but its slow and goes into Excel "Not Responding" for several seconds before completing. Can someone help me make this code more efficient?
Sub Refresh()
' Refresh Macro
' Checks the import data for accurate column headings, then refreshes the Standup Report with the new import data. Keeps Board Status Entries
Dim ColumnOrder As Variant, ndx As Integer
Dim Found As Range, counter As Integer
Dim rTemplate As Worksheet, nImport As Worksheet
Set rTemplate = ThisWorkbook.Worksheets("Standup Report Template")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlManual
On Error GoTo ErrHandler
'Move the "Standup Report Template" Worksheet to first position.
rTemplate.Move Before:=ActiveWorkbook.Sheets(1)
'Order Columns correctly
On Error Resume Next
Set nImport = ThisWorkbook.Worksheets(2)
nImport.Activate
ColumnOrder = Array("Formatted ID", "Name", "Schedule State", "Blocked", "Plan Estimate", "At Risk", "Added")
counter = 1
For ndx = LBound(ColumnOrder) To UBound(ColumnOrder)
Set Found = Rows("1:1").Find(ColumnOrder(ndx), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If Not Found Is Nothing Then
If Found.Column <> counter Then
Found.EntireColumn.Cut
Columns(counter).Insert Shift:=xlToRight
Application.CutCopyMode = False
End If
counter = counter + 1
End If
Next ndx
'Check to make sure all columns are present
On Error GoTo ErrHandler
If Range("A1").Value = "Formatted ID" And Range("b1").Value = "Name" And Range("c1").Value = "Schedule State" And Range("d1").Value = "Blocked" And Range("e1").Value = "Plan Estimate" And Range("f1").Value = "At Risk" And Range("g1").Value = "Added" Then
'insert formula to retain the current board state into column H of the new import file.
Application.Calculation = xlAutomatic
Range("H2").Formula = "=IF(ISERROR(MATCH(A2,'Standup Report Template'!B:B,0)),""NEW"",IF(ISBLANK(INDEX('Standup Report Template'!$B$1:$L$200,MATCH(A2,'Standup Report Template'!B:B,0),11)),""-"",INDEX('Standup Report Template'!$B$1:$L$200,MATCH(A2,'Standup Report Template'!B:B,0),11)))"
With Sheets(2)
.Range("H2").AutoFill .Range("H2:H" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With
Application.Calculation = xlManual
'clear old data from report
rTemplate.Activate
Application.Goto Reference:="ClearEntries"
Selection.ClearContents
'Delete Header Row of New Import file
nImport.Rows("1:1").Delete Shift:=xlUp
'Assign (instead of copy paste) new import data to the report template
rTemplate.Range("B4:H104").Value = nImport.Range("A1:G100").Value
'Justify Text
With Columns("B:B")
.HorizontalAlignment = xlRight
.VerticalAlignment = xlCenter
End With
With Columns("C:C")
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter
End With
With Columns("D:H")
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
With Range("B3:H3")
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
End With
'Copy Paste Revised Board State
nImport.Activate
ActiveSheet.UsedRange.Columns("H:H").Copy
rTemplate.Activate
Range("L4").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Delete import file
nImport.Delete
rTemplate.Activate
Range("L4").Select
ActiveWindow.Zoom = 80
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
MsgBox "New data has been imported. Please update the Board State as needed to finalize the report."
Else:
Rows("1:1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 7765734
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlAutomatic
MsgBox "The columns in your import table must be ordered as follows:" & vbCrLf & vbCrLf & "Formatted ID" & vbCrLf & "Name" & vbCrLf & "Schedule State" & vbCrLf & "Blocked" & vbCrLf & "Plan Estimate" & vbCrLf & "At Risk" & vbCrLf & "Added" & vbCrLf & vbCrLf & "Please make the appropriate changes to your import table and try again."
End If
Exit Sub
ErrHandler:
MsgBox "The Stand Up Report can't find your data. Please move data into the workbook before trying again."
End Sub
Don't use select on a range, it's extremely costly, here is an example to avoid it:
Columns("B:B").Select
With Selection
.HorizontalAlignment = xlRight
.VerticalAlignment = xlCenter
End With
Becomes:
With Columns("B:B")
.HorizontalAlignment = xlRight
.VerticalAlignment = xlCenter
End With
Note remove the .Select and the Selection.
I would probably also turn off calculation at the start of the code and back on at the end.
If you decide to do that, then you will need to do a manual Calculate after entering a formula like here:
Range("H2").Formula = "=IF(ISERROR(MATCH(A2,'Standup Report Template'!B:B,0)),""NEW"",IF(ISBLANK(INDEX('Standup Report Template'!$B$1:$L$200,MATCH(A2,'Standup Report Template'!B:B,0),11)),""-"",INDEX('Standup Report Template'!$B$1:$L$200,MATCH(A2,'Standup Report Template'!B:B,0),11)))"
With Sheets(2)
.Range("H2").AutoFill .Range("H2:H" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With
Application.calculate

Excel macro CSV issue

Im using a excel macro which generates a csv file with all my data to upload to gmail as contacts. When the file is uploaded to gmail contacts, the mobile number and the work number come correctly but the persons name comes in the notes box as "First Name: Yash".
Im attaching a sample csv file which is generated by the macro.
Download Sample CSV HERE
im using the following macro to generate the csv's:
Sub getcsv()
Application.ScreenUpdating = False
csvnewsheet
Dim myRange As Range
Dim NumRows As Integer
Set myRange = ActiveSheet.Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)
Range("E1").Select
ActiveCell.FormulaR1C1 = "First Name"
Range("E2").Select
ActiveCell.FormulaR1C1 = "=CONCATENATE(Reports!R[5]C2,"" "",Reports!R[5]C1)"
Range("E2").Select
Selection.AutoFill Destination:=Range("E2:E" & NumRows + 1)
Range("E2:E3").Select
Columns("E:E").EntireColumn.AutoFit
hide_format
Exporttocsv
DelSht
Application.ScreenUpdating = True
End Sub
Sub hide_format()
'
' hides name & place columns and then removed the formatting
'
'
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Columns("C:C").Select
Selection.Cut
Columns("A:A").Select
Selection.Insert Shift:=xlToRight
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub
Sub csvnewsheet()
Dim myRange As Range
Dim NumRows As Integer
Set myRange = Worksheets("Reports").Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange) + 3
Sheets.Add.Name = Worksheets("Reports").Range("A2").Value & "_CSV"
Worksheets("Reports").Range("A6:D" & NumRows).Copy Destination:=Worksheets(Worksheets("Reports").Range("A2").Value & "_CSV").Range("A1")
Worksheets(Worksheets("Reports").Range("A2").Value & "_CSV").Columns("A:D").AutoFit
End Sub
Sub Exporttocsv()
Dim MyPath As String
Dim MyFileName As String
MyFileName = Worksheets("Reports").Range("A2").Value & "_CSV"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Worksheets(Worksheets("Reports").Range("A2").Value & "_CSV").Copy
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder to Save the CSV"
.AllowMultiSelect = False
.InitialFileName = "" '<~~ The start folder path for the file picker.
If .Show <> -1 Then GoTo NextCode
MyPath = .SelectedItems(1) & "\"
End With
NextCode:
With ActiveWorkbook
.saveas Filename:=MyPath & MyFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
End Sub
Sub DelSht()
Application.DisplayAlerts = False
Sheets(Worksheets("Reports").Range("A2").Value & "_CSV").Delete
Application.DisplayAlerts = True
End Sub
This macro generates a new sheet with the data then will do the required changes and save as CSV and then delete that sheet.
i dont know where im going wrong...but the contact names just dont come in gmail... ive tried various other methods but it still didnt work...
Please help!
This is how Gmail suggests the format of the csv file.
-
this is how you have yours formatted.
You may have to have it formatted the way Gmail suggests.

Resources