I have a VBA that selects specific columns to create a chart. I was having an issue where certain columns would be omitted from the chart and I didn't know why. After troubleshooting, I found that once the omitted columns were converted from Text to Column that they worked. Any idea why?
I have tried to convert every column from Text to Column using a VBA but I get an error
...can only convert one column at a time...
Doing one at a time would take forever as I have hundreds of columns to do. Is there a VBA that can quickly process this?
Here is my code for creating the charts if it helps:
Sub Graph2()
' Graphs for monitoring
Dim my_range As Range, t, co As Shape
t = Selection.Cells(1, 1).Value & " - " & ActiveSheet.Name
Dim OldSheet As Worksheet
Set OldSheet = ActiveSheet
Set my_range = Union(Selection, ActiveSheet.Range("A:A"))
Set co = ActiveSheet.Shapes.AddChart2(201, xlLine) 'add a ChartObject
With co.Chart
.FullSeriesCollection(1).ChartType = xlXYScatter
.FullSeriesCollection(1).AxisGroup = 1
.FullSeriesCollection(2).ChartType = xlLine
.FullSeriesCollection(2).AxisGroup = 1
.SetSourceData Source:=my_range
'highlight final dot of data
.FullSeriesCollection(1).Points(.FullSeriesCollection(1).Points.Count - 1).ApplyDataLabels Type:=xlShowValue
.HasTitle = True
.ChartTitle.Text = t
'ResolveSeriesnames co.Chart
.Location Where:=xlLocationAsObject, Name:="Graphs"
End With
OldSheet.Activate
End Sub
Here is my answer.
Purpose:
Take a list of columns and apply the Range.TextToColumns method one by one as fast as possible.
Algorithm:
1. Create an array of needed columns;
2. Go through this array column by column and:
- 2.1 Check whether there is any data to the right;
- 2.2 Make sure to insert enough columns to preserve data on the right;
- 2.3 Apply Range.TextToColumns method.
Tested on:
Range of 200 rows and 200 columns filled with "Sample Data" text and randomly inserted "Sample Data Data Data Data Data" text to test with different delimiters quantity. Used space as delimiter:
Code:
Sub SplitColumns()
Dim rToSplit() As Range, r As Range
Dim i As Long, j As Long, k As Long
Dim sht As Worksheet
Dim delimiter As String
Dim consDelimiter As Boolean
Dim start As Single, total As Single
Dim delimitersCount() As Long
'========================== TESTING STUFF =======================================
' set working sheet
Set sht = ThisWorkbook.Sheets("Sheet2")
' re-create sample data (it is changed on each macro run)
sht.Cells.Clear
ThisWorkbook.Sheets("Sheet2").Cells.Copy Destination:=sht.Cells(1, 1)
' timer for testing purposes - start point
start = Timer
'======================== END OF TESTING STUFF ===================================
' Set the delimiter
' I've used space
delimiter = " "
' assign a ConsecutiveDelimiter state
consDelimiter = False
Application.ScreenUpdating = False
'=================== CREATING A LIST OF COLUMNS FOR SPLIT ========================
' create an array of columns to be changed
' at this sample I take all 200 columns
' you have to assign your own range which is to be splitted
With sht
For i = .Cells(1, Columns.Count).End(xlToLeft).Column To 1 Step -1
' add columns to an array
If Not .Cells(1, i) = "" Then
ReDim Preserve rToSplit(j)
Set rToSplit(j) = Range(.Cells(1, i), .Cells(Rows.Count, i).End(xlUp))
j = j + 1
End If
Next
End With
'=============== END OF CREATING A LIST OF COLUMNS FOR SPLIT ======================
'============================= PERFORMING SPLIT ===================================
' go through each column in array
' from left to right, because
' there may be a need to insert columns
For j = LBound(rToSplit) To UBound(rToSplit)
' check whether there is any data on the right from the top cell of column
' note - I'm checking only ONE cell
If Not rToSplit(j).Cells(1, 1).Offset(0, 1) = "" Then
' creating another array:
' purpose - check cells in column
' and count quantity of delimiters in each of them
' quantity of delimiters = quantity of columns to insert
' in order not to overwrite data on the right
For Each r In rToSplit(j).Cells
ReDim Preserve delimitersCount(k)
delimitersCount(k) = UBound(Split(r.Text, delimiter))
k = k + 1
Next
' get the maximun number of delimiters (= columns to insert)
For i = 1 To WorksheetFunction.Max(delimitersCount)
' and insert this quantity of columns
rToSplit(j).Cells(1, 1).Offset(0, 1).EntireColumn.Insert
Next
' split the column, nothing will be replaced
rToSplit(j).TextToColumns Destination:=rToSplit(j).Cells(1, 1), ConsecutiveDelimiter:=consDelimiter, Tab:=False, Semicolon:=False, Comma:=False, _
Space:=False, Other:=True, OtherChar:=delimiter
Else
' here I just split column as there is no data to the right
rToSplit(j).TextToColumns Destination:=rToSplit(j).Cells(1, 1), ConsecutiveDelimiter:=consDelimiter, Tab:=False, Semicolon:=False, Comma:=False, _
Space:=False, Other:=True, OtherChar:=delimiter
End If
' clear the delimiters count array
Erase delimitersCount
' go to next column
Next
' done
'========================= END OF PERFORMING SPLIT ===================================
' timer for testing purposes - time difference in seconds
total = Timer - start
Debug.Print "Total time spent " & total & " seconds."
Application.ScreenUpdating = True
End Sub
Hope that helps.
Related
I have a file with more then 1 sheet, where in the Reports Sheet I want to filter by ASBN products and then delete them, because I already processed it in another sheet, so I need to delete the initial ones in order to paste back the processed one.
Idea is that this deleting code which is working, but is taking for at least 20 minutes, because I want to delete 123 572 rows, do you have any idea how could I make this work faster?
I also tried to clear contents first and then to delete empty rows, but it's the same.
Here you find the code:
Public Sub Remove_ABSN()
Dim area As String
Dim start As Long
area = "ABSN"
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Application.EnableEvents = False
start = Worksheets("Reports").Cells(Cells.Rows.Count, 1).End(xlUp).Row
Worksheets("Reports").Range("$A$2:$AN" & start).AutoFilter Field:=8, Criteria1:=area, Operator:=xlFilterValues
Worksheets("Reports").Range("$A$2:$AN$" & start).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Sheets("Reports").ShowAllData
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
I think AutoFilter will be the fastest way to do it. Here are two sample scripts to try. You can see for yourself which one is faster.
Public Sub UnionDeleteRowsFast()
' Careful...delete runs on Sheet1
Dim sh2 As Worksheet
Set sh2 = Sheets("Sheet1")
Dim lastrow As Long
Dim Rng As Range
lastrow = Cells(Rows.Count, "B").End(xlUp).Row
For i = lastrow To 2 Step -1
If Cells(i, 2).Value = "Delete" Then
If Rng Is Nothing Then
Set Rng = Range("B" & i)
Else
Set Rng = Union(Rng, Range("B" & i))
End If
End If
Next
If Not Rng Is Nothing Then Rng.EntireRow.Delete
End Sub
Sub AutoFilterDeleteRowsFast()
' Careful...delete runs on ActiveSheet
With ActiveSheet
.AutoFilterMode = False
With Range("B4", Range("B" & Rows.Count).End(xlUp))
.AutoFilter 1, "*Delete*"
On Error Resume Next
.Offset(1).SpecialCells(12).EntireRow.Delete
End With
.AutoFilterMode = False
End With
End Sub
There is a way that is much faster.
Suppose a table of 100,000 lines (A1:B100001) with headers in line 1. Then delete condition refers to just 1 column (B).
One needs a auxiliar column (A) just to count the lines in the original order. Here I use autofill function.
So one can sort the table and after restore the original order.
Below there is a complete example, that generates randomly numbers from 1 to 10 (it's slow!), and after quickly delete all lines with values 3
Sub EraseValue()
Application.ScreenUpdating = False
Dim i As Long
Dim T1 As Single ' milisecs after booting (Start)
Dim T2 As Single ' milisecs after booting (End)
Dim LIni As Variant ' Initial line to delete
Dim LEnd As Variant ' Final line to delete
Const Fin = 100000 ' Lines in the table
Const FinStr = "100001" ' Last line (string)
Randomize (GetTickCount()) ' Seed of random generation
For i = 1 To Fin
Cells(i + 1, "B") = Int(Rnd() * 10 + 1) ' Generates from 1 to 10
If i Mod 100 = 0 Then Application.StatusBar = i
DoEvents
Next i
Application.StatusBar = False
Dim Table As Range
Dim Colu As Range
T1 = GetTickCount() ' Initial time
Cells(2, "A") = 1 ' Starting value
Cells(3, "A") = 2 ' Step
' Fill from 1 to 100,000 step 1
Range("A2:A3").AutoFill Destination:=Range("A2:A" & FinStr)
' Order by condition column
Table.Sort Key1:=Cells(1, "B"), Header:=xlYes
'One needs delete lines with column B = 3
'LIni: Search key that not exceed value 2 in the column
' (2 is immediately previous value)
'LEnd: Search key that not exceed value 3 in the column
'LIni and LFim is relative to 2 so add 1 for skip the header
'Add more 1 to Lini in order to get the first value in the column >= key
'
LIni = Application.Match(2, Colu, 1) + 2
LEnd = Application.Match(3, Colu, 1) + 1
If IsError(LIni) Or IsError(LEnd) Or LEnd < LEnd Then
MsgBox ("There is no lines to delete")
End
End If
Range(Rows(LIni), Rows(LEnd)).Delete (xlUp) ' Delete lines
Table.Sort Key1:=Cells(1, "A"), Header:=xlYes ' Restore initial order
T2 = GetTickCount() ' Get the final time
MsgBox ("Elapsed milisecs: " + Format((T2 - T1), "0"))
End Sub
In my old computer, it take a little bit more that 0.5 secs with 100,000 lines.
If one has a condition that involves 2 columns or more, one need to create an another auxiliary column with a formula that concatenate these columns related do desired condition and run the match in this column. The formula needs to usage relative references. For instance (assuming that the data of column C are string and is already filled with a header).
Cells(1,4) = "NewCol" ' New column D
Dim NewCol As Range
Set NewCol = Range("D2:D" & FinStr)
' Two previous columns concatenated. In line 2
' the formula would be "=Format(B2,"0")+C2" (B2 is a number)
NewCol.FormulaR1C1 = "=Format(RC[-2],"0") & RC[-1]"
NewCol.Copy
NewCol.PasteSpecial(XlValues) ' Convert all formulas to values
Application.CutCopyMode=false
So one usages the column D instead column B
I've been running this script for a while with not issues, and then today it broke. It's very basic as in I'm just filtering values from one tab and then copying and pasting them onto another tab in the top row. Suddenly though, it will paste the values and then repeat paste the values 19 more times for a total of 20 copy pastes.
Sheets("BSLOG").Select
Range("Q1").Select
Selection.AutoFilter Field:=17, Criteria1:="1"
Range("A1:Q5000").Select
Range("A1:Q5000").Activate
Selection.Copy
Sheets("PENDG TRADES").Select
Range("A1:Q300").Select
ActiveSheet.Paste
Try the next code, please. No need to select, activate anything. In this case, these selections do not bring any benefit, they only consume Excel resources:
Sub testFilterCopy()
Dim shB As Worksheet, shP As Worksheet
Set shB = Sheets("BSLOG")
Set shP = Sheets("PENDG TRADES")
shB.Range("Q1").AutoFilter field:=17, Criteria1:="1"
shB.Range("A1:Q5000").Copy shP.Range("A1")
End Sub
If you want to make the range dynamic (in terms of rows) I can show you how to initially calculate the existing number of rows and set the range to be copied according to it.
FaneDuru is right.
You can also try this code, which I prefer more:
Option Base 1 'This means all array starts at 1. It is set by default at 0. Use whatever you prefer,depending if you have headers or not, etc
Sub TestFilter()
Dim shBSLOG As Worksheet
Dim shPENDG As Worksheet
Dim rngBSLOG As Range
Dim arrBSLOG(), arrCopy()
Dim RowsInBSLOG&
Dim i&, j&, k&
Set shBSLOG = Worksheets("BSLOG")
Set shPENDG = Worksheets("PENDG TRADES")
With shBSLOG
Set rngBSLOG = .Range(.Cells(1, 1), .Cells(5000, 17))
End With
RowsInBSLOG = rngBSLOG.Rows.Count
arrBSLOG = rngBSLOG
ReDim arrCopy(1 To RowsInBSLOG, 1 To 17) 'set the size of the new array as the original array
k = 1 'k is set to 1. This will be used to the row of the new array "arrCopy"
For i = 1 To RowsInBSLOG 'filter the array. From the row "i" = 1 to the total of rows "RowsinBSLOG
If arrBSLOG(i, 1) = 1 Then 'if the first column of the row i is equal to 1, then...
For j = 1 To 17
arrCopy(k, j) = arrBSLOG(i, j) 'copy the row
Next j
k = k + 1 'next copy will be in a new row
End If
Next i 'repeat
With shPENDG
.Range(.Cells(1, 1), .Cells(k, 17)) = arrCopy() 'place the new array in the new sheet
End With
End Sub
TLDR: I need to alter a macro I wrote that selected a range of data based on user input. It originally used the whole range (just consecutive columns), but now needs to select every other column.
I have a sheet I'm working on where the user will input the number of years they want to look at an investment over. Basically, I have 50 years populated, and my macro hides the columns that exceed the specified number of years. Then using the remaining visible range, I have metrics that are run(Net Present Value, Internal Rate of Return). This all worked fine, but I now need to put a percentage column next to the initial data, meaning the metric formulas can't run using the consecutive ranges as they are. They need every other column of visible data.Here
Below is my code:
Sub HideCol()
'Prep the sheet
Sheets("Modeling").Visible = True
Sheets("Modeling").Activate
Columns("C:AZ").Select
Selection.EntireColumn.Hidden = True
myNum = Worksheets("InitialData").Range("LeaseTerm").Value
Range("C1").Select
numrows = Selection.Rows.Count
numColumns = Selection.Columns.Count
Selection.Resize(numrows + 0, numColumns + myNum - 1).Select
Selection.EntireColumn.Hidden = False
'Input dynamic calcs
'This is my problem here. calcrange selects consecutive columns, and I need to do every other
Dim calcrange As Range
Set calcrange = Union(Range("InvestmentOutlay"), Range(Range("B57"), Range("B57").End(xlToRight)))
Range("IRR").Formula = "=IRR(" & calcrange.Address & ")"
Dim npvRange As Range
Set npvRange = Range(Range("C57"), Range("C57").End(xlToRight))
Range("NPV").Formula = "=NPV(EconGrowth," & npvRange.Address & ")"
Dim outF As Range
Dim inF As Range
Set outF = Range("InvestmentOutlay")
Set inF = Range(Range("C57"), Range("C57").End(xlToRight))
Range("PB").Formula = "=PaybackPeriod(" & outF.Address & ", " & inF.Address & ")"
End Sub
Instead of:
Set calcrange = Union(Range("InvestmentOutlay"), Range(Range("B57"), Range("B57").End(xlToRight)))
just add every second column to the Union:
Dim c As Long
Set calcrange = Range("InvestmentOutlay")
For c = 2 To Range("B57").End(xlToRight).Column Step 2
Set calcrange = Union(calcrange, Cells(57, c))
Next
The first set of data is a snippet of may data (running into thousands of rows) in the first two columns.
The first column has repeated ticket numbers with different status. I want to have a unique row for each ticket and corresponding columns to have the various status(a transpose like). See below illustration:
Incident Number Measurement Status
INCIN0001910583 Detached
INCIN0001910583 Missed
INCIN0001908104 Detached
INCIN0001908104 Detached
INCIN0001908104 Missed
INCIN0001914487 Met
INCIN0001908444 Detached
INCIN0001908444 Detached
INCIN0001908444 Detached
INCIN0001908444 Met
INCIN0001910624 Met
INCIN0001910575 Detached
INCIN0001910575 Met
I'm looking for a macro (or formula) to achieve something like this:
INCIN0001910583 Detached Missed
INCIN0001908104 Detached Detached Missed
INCIN0001914487 Met
INCIN0001908444 Detached Detached Detached Met
INCIN0001910624 Met
INCIN0001910575 Detached Met
As Tom pointed out, below is the recorded macro I have been using to achieve this, pasting the transpose in the first occurrence of the unique Incident Number(column A) and then manually removing the blanks.(however it takes ages to complete it for thousands of rows)
Sub transpose_paste()
'
' transpose_paste Macro
'
' Keyboard Shortcut: Ctrl+t
'
Selection.Copy
Application.CutCopyMode = False
Selection.Copy
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 3
ActiveWindow.ScrollColumn = 4
ActiveWindow.ScrollColumn = 5
ActiveWindow.ScrollColumn = 6
ActiveWindow.ScrollColumn = 7
ActiveWindow.ScrollColumn = 8
ActiveWindow.ScrollColumn = 9
ActiveWindow.ScrollColumn = 10
ActiveWindow.ScrollColumn = 11
ActiveWindow.ScrollColumn = 12
ActiveWindow.ScrollColumn = 11
ActiveWindow.ScrollColumn = 10
ActiveWindow.ScrollColumn = 11
Cells(ActiveCell.Row, 14).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
ActiveWindow.ScrollColumn = 10
ActiveWindow.ScrollColumn = 9
ActiveWindow.ScrollColumn = 8
ActiveWindow.ScrollColumn = 7
ActiveWindow.ScrollColumn = 6
ActiveWindow.ScrollColumn = 5
ActiveWindow.ScrollColumn = 4
ActiveWindow.ScrollColumn = 3
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 1
End Sub
I'm not sure I understand why Tom gave you the advice he did. This wouldn't be a very good idea to get a recorded macro from because of the non-dynamic nature of recorded code as opposed to the dynamic nature of your data.
Here are two options. The first being what you asked for (run the 'PivotData_All' routine), the other being if you want to exclude non-unique items from the subsequent columns of data (run the 'PivotData_UniquesOnly' routine).
Sub PivotData_All()
With Worksheets("Sheet1")
Call PivotData(.Range("A2:B" & .Cells(.Rows.Count, 1).End(xlUp).Row), False)
End With
End Sub
Sub PivotData_UniquesOnly()
With Worksheets("Sheet1")
Call PivotData(.Range("A2:B" & .Cells(.Rows.Count, 1).End(xlUp).Row), True)
End With
End Sub
Sub PivotData( _
ByVal IncidentData As Range, _
Optional ByVal UniquesOnly As Boolean = False _
)
'
' Take data from a given range and pivot out data based on first column being incident numbers, second column being
' measurement status. Each unique incident will be given its own row and the measurment status will be pivoted out
' along columns on a new sheet.
'
' Syntax: PivotData(UniquesOnly)
'
' Parameters: IncidentData. Range. Required. A two-column set of data. Left column is incident number, right column
' is measurement status.
' UniquesOnly. Boolean. Optional. Specify whether second column of data should contain only unique values
' or not. If omitted False is passed.
'
Dim Incidents As Collection
Dim NewSheet As Worksheet
Dim Incident() As Variant
Dim IncidentItem As Variant
Dim IncidentTempValues() As Variant
Dim IncidentStep As Long
Dim IncidentMatch As Long
Dim IncidentKey As String
'// Change these as necessary
'// Get values into an array to start
IncidentTempValues = IncidentData.Value
'// Iterate through array to get unique values, append all measurements to individual array
Set Incidents = New Collection
For IncidentStep = LBound(IncidentTempValues, 1) To UBound(IncidentTempValues, 1)
IncidentKey = CStr(IncidentTempValues(IncidentStep, 1))
If InCollection(Incidents, IncidentKey) = False Then
Incident = Array(IncidentKey, IncidentTempValues(IncidentStep, 2))
Incidents.Add Incident, IncidentKey
Else
Erase Incident
Incident = Incidents.Item(IncidentKey)
IncidentMatch = 0
If UniquesOnly Then
On Error Resume Next
IncidentMatch = WorksheetFunction.Match(IncidentTempValues(IncidentStep, 2), Incident, 0)
On Error GoTo 0
End If
If IncidentMatch = 0 Then
ReDim Preserve Incident(LBound(Incident) To UBound(Incident) + 1)
Incident(UBound(Incident)) = IncidentTempValues(IncidentStep, 2)
Incidents.Remove IncidentKey
Incidents.Add Incident, IncidentKey
End If
End If
Next IncidentStep
'// Put values into new sheet
If Incidents.Count > 0 Then
Set NewSheet = Worksheets.Add
IncidentStep = 1
For Each IncidentItem In Incidents
NewSheet.Cells(IncidentStep, 1).Resize(1, UBound(IncidentItem) - LBound(IncidentItem) + 1).Value = IncidentItem
IncidentStep = IncidentStep + 1
Next IncidentItem
NewSheet.Cells.EntireColumn.AutoFit
End If
'// Message user upon completion
If Incidents.Count > 0 Then
MsgBox "New sheet created ('" & NewSheet.Name & "') with " & Incidents.Count & " record(s).", vbInformation, "Complete"
Else
MsgBox "Unable to create incident data.", vbExclamation, "Whoops!"
End If
End Sub
Public Function InCollection(CheckCollection As Collection, CheckKey As String) As Boolean
'
' Returns True if the specified key is found in the specified collection.
'
' Syntax: InCollection(CheckCollection,CheckKey)
'
' Parameters: CheckCollection. Collection. Required. The collection to search in.
' CheckKey. String. Required. The string key to search in collection for.
'
On Error Resume Next
InCollection = CBool(Not IsEmpty(CheckCollection(CheckKey)))
On Error GoTo 0
End Function
This would need to go into a standard module. Let us know if you need additional assistance with this.
Regards,
Zack Barresse
This procedure assumes the following:
Data ranges starts at A1, includes two columns and it's a continuous range of data (i.e. no blank rows in between, and column C is blank
Output data starts at D1
Sub Rng_List_Unique_Records()
Dim vSrc As Variant, sKey As String
Dim sStatus As String, aStatus As Variant
Dim lRow As Long, l As Long
With ThisWorkbook.Sheets(1)
Application.Goto .Cells(1), 1
Rem Set Array with Source Range Data
vSrc = .Cells(1).CurrentRegion.Value2
Rem Extract Unique Items
For l = 1 To UBound(vSrc)
If vSrc(l, 1) = sKey Then
Rem Same Incident - Add Measurement
sStatus = sStatus & ";" & vSrc(l, 2)
Else
If sStatus <> Empty Then
Rem Enter Measurements for Prior Incident
aStatus = Split(sStatus, ";")
.Cells(lRow, 5).Resize(, 1 + UBound(aStatus)) = aStatus
End If
Rem New Incident
lRow = 1 + lRow
sKey = vSrc(l, 1)
.Cells(lRow, 4) = sKey
sStatus = vSrc(l, 2)
End If: Next
Rem Enter Measurements for Last Incident
aStatus = Split(sStatus, ";")
.Cells(lRow, 5).Resize(, 1 + UBound(aStatus)) = aStatus
Rem Output Range Columns AutoFit
.Cells(4).CurrentRegion.EntireColumn.AutoFit
End With
End Sub
Suggest to visit the following pages to obtain a deeper understanding of the resources used:
Variables & Constants, Application Object (Excel), Excel Objects
With Statement, For Each...Next Statement, If...Then...Else Statement
Range Object (Excel), Worksheet Object (Excel)
Nevertheless let me know of any questions about the procedure
It's been a slow day so..... This will do what you want using vba. You could also achieve this as Scott has said above with formulas or even using a pivot table. However by the looks of the question you're looking for something dynamic which will expand automatically to include new incidents which the formulas won't do easily.
I've over commented it in the hopes that you will easily be able to understand for future modifications. This is probably not the only way of doing it and not necessarily the best.
Option Explicit
Sub transposeAndCombine()
' Declare all of the variable names and types we will be using
Dim inc As Object
Dim c As Integer: Dim i As Integer
Dim rng As Range
Dim f
Dim ws as worksheet
' Turns off screen updating - good practice for the majority of vba macros
Application.ScreenUpdating = False
' Declare worksheet
set ws = ThisWorkbook.Sheets("Sheet1")
' Change Sheet1 to relevant sheet
' You'll also need to change all 4's that are detailed below to your relevant destination.
' I put all the processed data into Column D in my example
' starting from row 2 to leave a row for a header
With ws
' Declare range that we are going to be considering (where the raw data is)
Set rng = Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
' Loop through that data
For Each inc In rng
' Find if data exists in destination
Set f = .Columns(4).Find(inc.Value, LookIn:=xlValues)
' If it exists assign the row number to a variable, if not add it to the end
If Not f Is Nothing Then
i = f.Row
Else
i = .Cells(.Rows.Count, 4).End(xlUp).Row + 1
.Cells(i, 4) = inc.Value
End If
' find last column that has been used
c = .Cells(i, .Columns.Count).End(xlToLeft).Column + 1
' add the Status value to the row
.Cells(i, c) = inc.Offset(0, 1)
' Loop back for next data entry
Next inc
End With
' Turn back on screen updating for normal behaviour
Application.ScreenUpdating = True
End Sub
This puzzle is getting on my nerves now, as a beginning VBA Excel user with a lot of ambition to automize things... (Maybe a bit too ambitious :) )
The things I've managed this far are: creating a new file with a worksheet for every company, containing all current available data.
A control sheet where I can select which stakeholder should receive which sheet(s), with which text and when.
This all works fine but I want to add graphs to the data to show what's going on over time.
The problem is:
- looping through a variable set of data every month there's a new column added so the range of columns should be flexible.
- the number of rows per company isn't predefined and may vary month-over-month
- the number of companies where a worksheet is created for may vary as well
My intention is to:
- create graphs for each unique value in Column D
- name the graphs (title) with the unique value in column D
- name the new created tab with the name of the Company in column A (let's say: 'Company A - graphs' as a sheet name)
- include all graphs from the current sheet in one sheet (the information on the current sheet is of ONE company)
- go to the next sheet and do the same (loop) until all sheets are done
- add another sheet with all sheet names that are currently in the file (existing + created)
- the label of the Y-values is in column G ('Name')
- the Y-values are in the columns H and further and row 2 and all the way down (flexible)
- the headers are in row 1 --> only the months (H >>) should be included on the X-axis
- So the information in the columns A:F shouldn't be used other than mentioned above
I got quite a piece of script but I'm on a dead end street. Any help would be very much appreciated!
If you have any questions please let me know.
Many many thanks in advance!
Wouter :-)
P.S.: Here's the file: http://we.tl/786d6b6cs0
Sub WJS_CreateGraphs()
Response = MsgBox("Are you sure you want to create graphs for all worksheets?", vbYesNo, "Graph Creator")
If Response = vbNo Then
Exit Sub
End If
' ------------------------------------ Now we will create pivot tables for all scenario's
Dim WS_Count As Integer
Dim C As Integer
' Set WS_Count equal to the number of worksheets in the active workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
For C = 1 To WS_Count
Dim I As Integer
Dim selecta As Range
Dim grFilter As Range, grUniques As Range
Dim grCell As Range, grCounter As Integer
Dim arow As Integer
Dim acol As Integer
Dim StartPoint As Integer
Dim EndPoint As Integer
Dim rStartPoint As Integer
Dim rEndPoint As Integer
ActiveSheet.Range("D1").Select
Set selecta = Range(Selection, ActiveCell.SpecialCells(xlLastCell))
Set grFilter = Range("D1", Range("D" & Rows.Count).End(xlUp))
With grFilter
' Filter column A to show only one of each item (uniques) in column A
.AdvancedFilter Action:=xlFilterInPlace, Unique:=True
' Set a variable to the Unique values
Set grUniques = Range("D2", Range("D" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible)
' Filter, Copy, and Paste each unique to its' own sheet in the new workbook
For Each cell In grUniques
counter = counter + 1
'NOTE - this filter is on column D(field:=1), to change
'to a different column you need to change the field number relative to the Unique Value range above
grFilter.AutoFilter field:=1, Criteria1:=cell.Value
'********************************************************************************************************************************
temp_StartPoint = 2
temp_EndPoint = ActiveSheet.UsedRange.Rows.Count
For arow = temp_StartPoint To temp_EndPoint
StartPoint = 2
EndPoint = ActiveSheet.UsedRange.Rows.Count
FirstColumn = 7
LastColumn = ActiveSheet.UsedRange.Columns.Count
' remember the sheet to return to, this is the current active sheet --> after creating a graph VBA will return to this sheet
MyPrevSheet = ActiveSheet.name
Charts.Add
ActiveChart.ChartArea.Select
ActiveChart.ChartType = xlLine 'Type of graph
' Return to previous sheet
If Len(MyPrevSheet) > 0 Then
Sheets(MyPrevSheet).Activate
Else
MsgBox "You have not switched sheets yet since opening the file!"
End If
ActiveChart.SetSourceData Source:=Range(Cells(StartPoint, FirstColumn) & ":" & Cells(EndPoint, LastColumn))
', PlotBy:=xlRows 'data source
ActiveChart.SeriesCollection(1).XValues = ActiveSheets.Range(FirstColumn & "1:" & Cells(LastColumn, 1))
'naming the x-axis
ActiveChart.SeriesCollection(1).name = "Spwr" ' Name of 1st data series 1
ActiveSheet.ShowAllData
On Error Resume Next
With ActiveChart.SeriesCollection(1) 'put labels on 1st data series
.HasDataLabels = True
.DataLabels.NumberFormat = "##"
End With
With ActiveChart.Axes(xlValue)
.HasMajorGridlines = False
.HasMinorGridlines = False
End With
ActiveChart.PlotArea.Select ' Background of graph
With Selection.Border
.ColorIndex = 16
.Weight = xlThin
.LineStyle = xlContinuous
End With
Selection.Interior.ColorIndex = xlNone
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(2).name = "salespower"
ActiveChart.SeriesCollection(2).Values = ActiveSheets.Range("G2:m2")
With ActiveChart.SeriesCollection(2) 'put labels on 2nd line
.HasDataLabels = True
.DataLabels.NumberFormat = "##"
End With
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(3).name = "Tests"
ActiveChart.SeriesCollection(3).Values = ActiveSheets.Range("G2:m2")
With ActiveChart.SeriesCollection(3) 'put labels on 3rd line
.HasDataLabels = True
.DataLabels.NumberFormat = "##"
End With
ActiveChart.Legend.Position = xlLegendPositionBottom
ActiveChart.HasTitle = True
ChartTitle = "Naam van de chart"
Next arow
Next cell
rngFilter.Parent.AutoFilterMode = False
Application.ScreenUpdating = True
'***********************************************************************************************************************************************
End With
Next C
End Sub