VBA Excel Coding extension and modification - vba

I have made an assessment system for a project using Microsoft Excel and I wanted to to make it so that you could use the same drop down menus twice.
Enter the data and then for the spreadsheet to retain that data and allow you to overwrite it but still maintain the data but to be dependant on the value of a data validation drop down list.
I have been given the code for this and it works however only for a section of the spreadsheet.
I wish to have the same effect however use a different drop down menu and for it to affect a different section of the spreadsheet.
Please feel free to ask for the actual spreadsheet or code.
Here is the Code:
Option Explicit
Public Sub Worksheet_Change(ByVal Target As Range)
' This Sub is a standard VBA event handler. It is automatically invoked
' every time the content of any cell in this worksheet changes
' We are only interested if the user picks a different type of
' grade. A named range GradeType was created to name this cell.
' This allows the worksheet format to change without having to change
' this code.
If Target.Address = Sheet1.[GradeType].Address Then
' So the user doesn't see each invidual worksheet change as it happens
Application.ScreenUpdating = False
' Where the current data will be saved to
' These are in the first row, so the number of columns has
' to be determined on the fly based on how much data is there
Dim FirstSaveTo As Range
Dim LastSaveTo As Range
' Where the previous saved data will be restored from
Dim LastRestoreFrom As Range
Dim FirstRestoreFrom As Range
' Use variables to define the relevant spaces in the Save sheet
' depending on what grade type the user selected
If [GradeType] = "Attainment" Then
Set FirstSaveTo = Save.[AttainmentStart]
Set LastSaveTo = Save.[AttainmentEnd]
Set FirstRestoreFrom = Save.[EffortStart]
Set LastRestoreFrom = Save.[EffortEnd]
Else
Set FirstRestoreFrom = Save.[AttainmentStart]
Set LastRestoreFrom = Save.[AttainmentEnd]
Set FirstSaveTo = Save.[EffortStart]
Set LastSaveTo = Save.[EffortEnd]
End If
' Save current data
' Clear previously saved data
Save.Range(FirstSaveTo, LastSaveTo).EntireColumn.ClearContents
' Copy current data
Sheet1.Range(Sheet1.[AssessmentFirst], Cells(Sheet1.UsedRange.Rows.Count, Sheet1.[AssessmentLast].Column)).Copy
' Paste
FirstSaveTo.PasteSpecial xlPasteValues
' Restore saved data
' Clear current data
Sheet1.Range(Sheet1.[AssessmentFirst], Cells(Sheet1.UsedRange.Rows.Count, Sheet1.[AssessmentLast].Column)).ClearContents
' Copy saved data
Save.Range(FirstRestoreFrom, Save.Cells(Save.UsedRange.Rows.Count, LastRestoreFrom.Column)).Copy
' Paste saved data
Sheet1.[AssessmentFirst].PasteSpecial xlValues
' Deselect copy area
Application.CutCopyMode = False
' Put user back where he started
[GradeType].Select
Application.ScreenUpdating = True
End If
End Sub

Your code is getting currently applied to the Named Range GradeType.
If you want to apply your code to another drop-down list, you can change this line:
If Target.Address = Sheet1.[GradeType].Address Then
And adapt it to whatever you need (don't forget to create a new named range first).
In order to do this, have a look at:
what is a named range and how to define it
how you can learn some vba: Programming Excel and VBA: Basic Syntax and Examples Tutorial

Related

Fire a macro on formula result change across two workbooks

My problem is quite simple : I have two workbooks (let's say they are wb1 and wb2).
On ws2 of wb2, I have on Range("A1") a formula like ='[wb1.xlsm]ws1'B1 . So, when B1 on ws1 of wb1 changes, A1 on ws2 of wb2 changes too (that's the goal).
My problem is how to fire a macro when the value of A1 on ws2 changes ? Worksheet_Change doesn't fire, and Workbook_SheetChange isn't fitting in this case...
EDIT By the way, Worksheet_Calculate doesn't fit too. Indeed, I don't know where the value on ws2 will change.
Before answering your question I feel compelled to highlight that there are lots of really good reasons to avoid linked workbooks. It always ends in pain, misery, lost data and long wasted hours spent trying to track data back to its source. Rant over, here is how you can ignore my advice.
This code uses the VBA collection object, which is pretty rubbish. VBScript includes the much better dictionary object, which you can use within VBA. I would highly recommend investigating this further...
There are two parts to the code. The first element is run once. It finds and begins tracking every external reference in a given sheet.
' Find all formulas that point to external workbook.
' Store current value.
Sub Initialise()
Dim c As Range ' Used to loop over all cells, looking for external.
' Ready collection for use.
Set ExternalFormula = New Collection
For Each c In [Sheet1].UsedRange
' Check if external, will start: =[
If c.HasFormula And c.Formula Like "=[[]*" Then
' Value added to collection contains key, for later use.
' Collections cannot return keys.
' Dictionaries are better, but require an external reference.
ExternalFormula.Add c.address & "~~~" & c.Value, c.address
End If
Next
End Sub
The next section is included in the Calculate event. Calculate doesn't provide the updated cell address. But using the ExternalFormula collection we can figure out which cell has been updated.
' Check external formula for changes.
Private Sub Worksheet_Calculate()
Dim c As Integer ' Used to loop over forumla.
Dim address As String ' A1 style address of current forumla.
Dim oldValue As String ' Value before any updates.
' Loop over stored values, looking for change.
If ExternalFormula.Count > 0 Then
For c = 1 To ExternalFormula.Count
' Extract address and old value.
address = Split(ExternalFormula.Item(c), "~~~")(0)
oldValue = Split(ExternalFormula.Item(c), "~~~")(1)
' Check for changes.
If [Sheet1].Range(address).Value <> oldValue Then
' Change found.
MsgBox address & " updated", vbInformation
' Update stored value.
ExternalFormula.Remove address
ExternalFormula.Add address & "~~~" & [Sheet1].Range(address).Value, address
End If
Next
End If
End Sub
Using the dictionary object would dramatically reduce the number of lines of code in that function.
Don't forget to declare ExternalFormula at the workbook or worksheet level.
Private ExternalFormula As Collection ' Stores all external forumulas.

How to Find selected Active cell highlighted with Color and copy the data provided in the cell above to some special assigned cell

I am new to VBA so if somebody help me to solve my problem then I shall be really grateful as I am stuck with it.
enter image description here
Please have a look at the attached picture below and if somebody provide me code for VBA then it will be really helpful for me. Task contains following steps.
1- In row 11 dates are provided in corresponding columns. Like 16/11, 17/11, 18/11 etc.
2- From row (12 to 29) I have different tasks to do are provided.
My task is.
1- When I select any cell/ box by filling it with any color the date available in the (row 10) above that cell (automatically goes/copies) to the specified cell mentioned for that task.
For Example: I select Row 21 AQR presentation cell and highlight it by filling it with color so the date above that cell automatically goes/copies to specified cell mentioned above for AQR presentation and similarly I have to do with every cell.
Request:
I need a code that detects the active cell which is highlighted and sends the date above that cell to a specified folder mentioned for that above.
Please see the figure for more clear understanding.
I shall be grateful if somebody help me in providing the code for this.
I do not believe that an exact match on your requirement is possible; certainly I do not know how to provide an exact match. However, I believe something very similar is possible which I think is more convenient than your request.
You need to use event routines. Excel identifies “Open workbook”, “Activate worksheet”, “Change selection” and many others as events. For any Excel event, you can write a routine in VBA which Excel will execute when that event occurs.
If you open Excel’s VB Editor and click F2 you get a list of all the classes and their members. Scroll down the Classes list until you reach “Worksheet”. The list on the right will display all member of the Worksheet class. Those with a lightning symbol against them are events: Activate, BeforeDelete, BeforeDoubleClick, BeforeRightClick, Calculate and so on. If you type “excel vba worksheet before double click event” into your favourite search engine, you will get web pages that explain the event and usually give an example of a routine for the event. I find the documentation a little vague and I usually have to experiment with an unfamiliar event.
I have written event routines for the WorkBook Open event and the Worksheet Activate, Before Right Click and Selection Change events. Unfortunately, there is no “Worksheet Change Cell Colour” event so I have used the “Worksheet Before Right Click” event instead.
With the VB Editor open, you will see the Project explorer down the left hand side. If you cannot see it, click Ctrl+R. What you will see will be something like:
- VBAProject(Xxxxx.xlsm)
- Microsoft Excel Objects
Sheet1 (Kick off)
Sheet2 (Sheet2)
ThisWorkbook
You will have more worksheets, perhaps some user forms and some modules but they do not matter for the moment. If you can see a plus where I have shown a minus, click it to expand the list. I have created a copy of your kick-off worksheet which I have named “Kick off”. You probably have a different name but I will call it “Kick off”. Click “Sheet1 (Kick off)” and a white area will appear to the right. This is a code area reserved for this worksheet. There is a similar code area for every worksheet. If you click “ThisWorkbook”, you will get another code area. You can use this code area as an ordinary module but I advise against it. This code area should be reserved for certain workbook level routines.
Place this code within the ThisWorkbook code area:
Option Explicit
Sub Workbook_Open()
If ActiveSheet.Name = "Kick off" Then
Worksheets("Sheet1").Activate
Worksheets("Kick off").Activate
End If
End Sub
A routine with the name Workbook_Open in this code area will be automatically executed when the workbook is opened. Replace “Kick off” with your name for this worksheet and replace “Sheet1” with the name of any of your other worksheets.
If worksheet “Kick off” was active when the workbook was saved, its Activate routine is not executed automatically when the workbook is opened. The sole purpose of this code is to force execution of the “kick off” activate routine.
The code below all belongs in the code area for Worksheet “Kick off”. This code will not do exactly what you want so I will attempt to explain it in sufficient detail for you to adapt it to your requirements,
My code starts with some constants for rows and columns. For example:
Const RowDate As Long = 11 ' Row holding dates
Currently, you have your dates in row 11 but this could easily change as you develop your system. If you amend your worksheet so row 13 holds the dates, simply update this constant statement and your code is fully updated. So much easier than scanning your code for all uses of the literal 11.
Next I have some constants for colours. If you do not like my colours, amend these constant statements.
Next are some Dim statements. A variable declared within a routine, is destroyed when the routine exits. A variable declared outside a routine has a longer life. I do not know if these variables last until the workbook is closed or until another worksheet is activated. It does not matter; they last long enough to allow me to pass values from one call of an event routine to another call.
Next is Private Sub Worksheet_Activate(). If your users switch to another worksheet, this routine will be called automatically when they switch back. It records the position of the active cell and loads three arrays. The three arrays and their values are:
Array entries -> 0 1
RowActionSrc 16 21
RowActionDest 2 3
ColActionDest 25 25
The way these arrays are used is a common technique with experienced programmers but might be new to you. You want special actions to occur if a selection is made on row 16 or 21. These rows may change and similar actions may be required for other rows later. By having a single statement load these row numbers into an array, it is easy to change them or add to them. If a cell on row 16 is selected, you want its date copied to row 2, column 25. If a cell on row 21 is selected, you want its date copied to row 3, column 25. These destinations may not be what you want but they are easy to change so that does not matter. I have coded Worksheet_BeforeRightClick to use the numbers in these arrays to move the required dates to the required cells.
Stepping over Worksheet_BeforeRightClick for the moment, the last routine in this code is Worksheet_SelectionChange. I was not sure if this was a good idea. The functionality provided by this routine is the cause of most of the complexity in this code. I have decided to keep the functionality because I believe it is helpful and because it gives a very good demonstration of what event routines can do. This is an image of my kick off worksheet:
It is a little small but adequate for the purpose and does not exactly match yours but is close enough. The active cell is currently cell Z21. You will notice the task and date for this cell are coloured. When I first started, I found it difficult to match the active cell to its task and date. Colouring the task and the date made it much easier. This is what Worksheet_SelectionChange does. When the user moves the active cell, this routine is called automatically to remove the colouring from the old task and date and colour the new task and date. As I said, I believe this functionality is both helpful and a good demonstration of how you can use event routines to tailor the Excel experience.
Returning to Worksheet_BeforeRightClick; this is the routine that provides the functionality that is the closest match I can achieve to what you requested. As I said, there is no event based on colouring a cell. Even if there was, I am not sure I would find it convenient. I would have to select the Home tag then Fill Colour then the colour I wanted before the event would be triggered. With the Before Right Click event, I select the cell I wish to be active using the arrow keys or the mouse or F5 or however I wish. I then click the right mouse key. The event routine colours the cell with the standard colour and copies the date.
Experiment with my code. Try to work out how it achieves its objectives. Come back with questions as necessary but the more you can work out for yourself, the quicker you will develop your own skills.
Option Explicit
' I define these column and row numbers as constants in case they change.
' If they do change, one amendment here and the code is updated. If the
' literal is used in the code, you have to search for and fix every use
' to update the code.
Const ColDateFirst As Long = 3 ' The first column with a date
Const ColTaskName As Long = 1 ' Column holding task names
Const RowDate As Long = 11 ' Row holding dates
Const RowTaskFirst As Long = 12 ' First row containing tasks
' Warning: If you change any of these colours, the values are BBGGRR which
' is Excel's standard and not RRGGB which is everyone else's standard.
Const ClrCrntHeader As Long = &H99CCFF ' Tan
Const ClrSelectedCell As Long = &HFFFF& ' Yellow
' The position of the active cell is recorded in these variable so
' when the active cell changes the old position is known. This is
' necessary to correctly maintain the row and column headers. If
' the row and column headers were not highlighted, these variables
' would not be needed.
Dim ColPrev As Long
Dim RowPrev As Long
' These arrays are loaded by Worksheet_Activate(). See that routine
' for an explanation of these arrays.
Dim RowActionSrc() As Variant
Dim RowActionDest() As Variant
Dim ColActionDest() As Variant
Private Sub Worksheet_Activate()
' This routine is called when the worksheet is activated (selected)
' * If the active cell is within the monitored area, the header row and
' column will already be hightlighted. Record the current position of
' the active cell in ColPrev and RowPrev.
' * Load RowAction and ColAction arrays
' * The monitored area is ColDatFirst and right and RowTaskFirst amd down.
Application.EnableEvents = False
If ActiveCell.Row >= RowTaskFirst And ActiveCell.Column >= ColDateFirst Then
' Active cell was within the monitored area when the workbook was closed or
' the user switched to another worksheet. The appropriate row and column
' headers will still be highlighted.
ColPrev = ActiveCell.Column
RowPrev = ActiveCell.Row
Else
' The active cell was outside the monitored area. No row or column header
' is highlighted
ColPrev = 0
RowPrev = 0
End If
' If the active cell is right clicked when it is in one of the rows
' listed in RowActionSrc:
' 1) The active cell is coloured ClrSelectedCell
' 2) The date above the active cell is copied to the row and column
' specified in the cell specified by the matching positions
' in RowActionDest and ColActionDest.
RowActionSrc = VBA.Array(16, 21)
RowActionDest = VBA.Array(2, 3)
ColActionDest = VBA.Array(25, 25)
' For example:
' * If cell(16,20) is right clicked, the date in cell(11, 20) is copied
' to cell(2,25).
' * If cell(21,27) is right clicked, the date in cell(11, 27) is copied
' to cell(3,25).
Application.EnableEvents = True
End Sub
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
' * The active cell has been right clicked.
' * If the active cell is within the monitored area and if active row is
' specified in RowActionSrc, copy the data above the active cell to the
' specified destination cell.
Dim CellColoured As Range
Application.EnableEvents = False
Dim InxC As Long
If ActiveCell.Row >= RowTaskFirst And ActiveCell.Column >= ColDateFirst Then
' Active cell was within the monitored area
For InxC = 0 To UBound(RowActionSrc)
If RowActionSrc(InxC) = ActiveCell.Row Then
' The active cell is in a row for which the date above it is to be
' copied to a specified destination. In addition, the active cell is
' to be coloured
' First remove colour from any previously selected cell
Application.FindFormat.Interior.Color = ClrSelectedCell
Do While True
' What:="*" will only match cells with a value
' What:="" will match cells with or without a value
Set CellColoured = Rows(ActiveCell.Row).Find(What:="", SearchFormat:=True)
If CellColoured Is Nothing Then
Exit Do
End If
CellColoured.Interior.ColorIndex = xlNone ' Remove colour
CellColoured.Value = "" ' Remove value if any
Loop
' Colour selected cell
Cells(ActiveCell.Row, ActiveCell.Column).Interior.Color = ClrSelectedCell
' Move date for active column to specified cell
Cells(RowActionDest(InxC), ColActionDest(InxC)).Value = Cells(RowDate, ActiveCell.Column).Value
End If
Next
End If
Cancel = True ' Surpress default action for Right Click
Application.EnableEvents = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.EnableEvents = False
' A new cell has been selected; that is, there is a new active cell.
If ColPrev <> 0 Then
' Remove highlighting from previous task name and date
Cells(RowPrev, ColTaskName).Interior.ColorIndex = xlNone
Cells(RowDate, ColPrev).Interior.ColorIndex = xlNone
End If
If ActiveCell.Row >= RowTaskFirst And ActiveCell.Column >= ColDateFirst Then
' Active cell is within the monitored area
ColPrev = ActiveCell.Column
RowPrev = ActiveCell.Row
' Highlight task name and date
Cells(RowPrev, ColTaskName).Interior.Color = ClrCrntHeader
Cells(RowDate, ColPrev).Interior.Color = ClrCrntHeader
Else
ColPrev = 0 ' No previous active cell
RowPrev = 0
End If
Application.EnableEvents = True
End Sub
Explanation of additional functionality
The original code would colour a cell selected with a right click but would not remove the colour from a previously selected cell. The new code locates any cells in the active row coloured ClrSelectedCell (= Yellow = &HFFFF&) and removes the colour and the value if any.
Find is normally used to search for values but it is possible to search for formats. If there is any decent documentation on the format search functionality, I have failed to find it. The extra code has been developed through experimentation rather than by following official instructions. This code has been tested using Excel 2016 but I have no reason to believe it will not work with earlier versions.
The changes are the inclusion of a new variable (Dim CellColoured As Range) and the inclusion of this code just before the newly selected cell is coloured:
Application.FindFormat.Interior.Color = ClrSelectedCell
Do While True
' What:="*" will only match cells with a value
' What:="" will match cells with or without a value
Set CellColoured = Rows(ActiveCell.Row).Find(What:="", SearchFormat:=True)
If CellColoured Is Nothing Then
Exit Do
End If
CellColoured.Interior.ColorIndex = xlNone ' Remove colour
CellColoured.Value = "" ' Remove value if any
Loop
There should only be one previously coloured cell but this code loops so all previously coloured cells are cleared of colour and value.
Note: I clear the colour using ColorIndex = xlNone rather than Colour = vbWhite. If you set the colour of a cell to white, you lose the borders but you do not if you set the colour index to none.
Define a function in VBA:
Function NOTWHITE(rng As Range) As Boolean
Application.Volatile
If rng.Interior.ColorIndex = xlNone Or rng.Interior.Color = vbWhite Then
NOTWHITE = False
Else
NOTWHITE = True
End If
End Function
Then put into D12 the following formula and copy-paste to all other cells you wish to behave like that:
=IF(NOTWHITE(D12); D$11; "")
However you need to recalculate the sheet by F9 after each change.

Running a procedure based on cell values in another workbook

I have six different forms, all of which contain the same information but in different places. These forms are sent to me by other parties and once I receive them, I open the file, determine which form I am dealing with, then run the appropriate transposition macro to upload the information to my summary workbook.
I would like to be able to check cells B4, B8, B10, B15 and B20 to ascertain what form I am dealing with, then have the appropriate transposition macro run on its own.
Can someone please help me set this up?
Right now I have the following:
' I use the file path to identify the form that I want to copy information from
Dim FilePath As String
Dim InputTemplate As Workbook
Dim UploadForm As Workbook
Dim Analysis As Worksheet
Dim supplierdata As Worksheet
Dim TemplateType
Set UploadForm = ActiveWorkbook
FilePath = UploadForm.Sheets("Summary").Range("D4").Value
Set InputTemplate = Workbooks.Open(FilePath)
Set Analysis = UploadForm.Sheets("Analysis")
Set supplierdata = InputTemplate.Sheets("Supplier Input Template")
How do I say that if B4.value=Company Name, B8.value=Date, B10.value = Currency... then run the correct transposition macro?
The most-condensed you could do it might be something like:
'....
Set supplierdata = InputTemplate.Sheets("Supplier Input Template")
With supplierdata.Columns(2)
If .Cells(4).value = "Company Name" And .Cells(8).Value="Date" _
And .Cells(10).Value = "Currency" Then
'handle this type of form
End If
End With
If you have many of these types of checks to perform, then you could consider using a "metadata-driven" approach, where you list on a worksheet the Ranges and the corresponding content, and loop over that information to detect the type of report. That would be more coding up-front but easier ongoing maintenance once you have it set up.

How to copy a row of data from one sheet to another based on cell data

I'm using excel for a project management tool. Right now I have a large table with a series of drop down menus for users to select who is responsible for the project, due dates, etc.
What I'd like to be able to do is copy over the full row (all project data) to each user individual page.
Say "Fred" creates a project and assigns it to "Tom" on the master page, I want Tom's sheet to autopopulate with the project details so instead of scrolling through the list to find him own name, he can click on his tab at the bottom of the master list and see all of his projects.
I've read through several questions somewhat similar and have yet to find anything that works.
For reference, the names are all in column F and there are currently 12 names that user can select from to assign a project; therefore, there are also 12 blank pages/sheets tabbed at the bottom next to the master page tab.
Thanks for any help you may be able to offer!
This macro might work for you - you need to put the right column number in for the filter...
It has to be put in the "Workbook" code (not a module - otherwise the event handling won't work).
It will run every time you change sheets - and will copy the most up to date information into the project leader's tab. If you have "other" sheets that you don't want this to act upon, you must catch the names of those sheets in the same line where code currently tests for "Master".
Changes needed to adapt to your specific situation - I'm sure you can handle it.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim prjLeader As String
Dim wholeRange As Range
prjLeader = Sh.Name
If prjLeader = "Master" Then Exit Sub ' whatever the name of the master sheet is...
On Error GoTo outtahere
Application.EnableEvents = False
Application.ScreenUpdating = False
Sh.UsedRange.Clear ' remove "old" information
ActiveWorkbook.Sheets("Master").Activate
Set wholeRange = ActiveSheet.UsedRange
wholeRange.AutoFilter Field:=6, Criteria1:=prjLeader ' use the field where proj leader name is (F = 6)
wholeRange.Copy ' copy all filtered data
Sh.Activate ' and paste it in project leader's sheet
Range("A1").PasteSpecial
outtahere: ' handle errors - back to sheet, turn events back on
Sh.Activate
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

Excel 2003(VBA) - Custom Identifier / Function / UDF

I'm currently rewriting a small stock system for my work, and trying to speed up the program as it's dog slow and I have only been doing VBA for 2 weeks now.
In Excel 2003 Edition.
My issue (I think) is creating a identifier(s).
I have two and they are as follows:
Dim QuickView As String
QuickView = ActiveWorkbook.Range("a1:c200").Copy
Dim Stock As String
Stock = ActiveWorkbook.Range("c1:c200").Copy
My users currently select a file(WORKBOOK) from an open dialogue and I am importing the data in the ranges specified.
However, when I come to call these functions I get "Object does not support this property or method".
im unsure if this should be a UDF, as i can't see anywhere where you can write your own VBA function opposed to write a function in VBA for Excel to use.
In your two examples, both "QuickView" and "Stock" should be variants, not strings.
Dim Stock As Variant
Stock = ActiveWorkbook.Range("c1:c200").Copy
Remember, you do NOT need to assign ranges to a variable in order to copy (or cut) cell values to another location. Instead, you can do it like this:
ActiveWorkbook.Sheets("Sheet1").Range("c1:c200").Copy
ThisWorkbook.Sheets("Sheet1").range("c1")
The convention is copy_from [SPACE] put_it_here.
Note: In my example above, the values would be copied into Sheet1 of the workbook that contains the running code. The workbook running the VBA is always ThisWorkbook.
As #timbur said, you can copy a range without assigning it first. If you want to assign it, the variable must be of type Range (or Variant) and you must assign using Set, like any object assign.
Dim stock as Range 'or Variant, but Range is better
Set stock = ActiveWorkSheet.Range("c1:c200")
'copy, and optionally paste at once
stock.Copy Destination:=ThisWorkbook.Sheets("Sheet1").range("c1")
eSolved it guys, thanks for your answers :-D
Sub Button1_Click()
Dim FileOpened As Boolean ' Holds True or False value
Dim SourceRange As Range
Dim TargetRange As Range
Dim MasterWorkbook As Workbook
Dim Row As Integer
' Remember the current workbook we are clicking the button from.
Set MasterWorkbook = ActiveWorkbook ' Use Set = for all complex types.
' Identify file to open.
ChDrive "C:"
ChDir "c:\"
On Error Resume Next ' Temporarily ignore errors in situation when user says no to opening the same master file a second time.
FileOpened = Application.Dialogs(xlDialogOpen).Show
On Error GoTo 0 ' Reinstates normal error reporting.
' Don't process the file if the user cancels the dialog.
If FileOpened Then
' The opened file automatically becomes the new active workbook and active worksheet.
Set SourceRange = ActiveSheet.Range("c1:c394")
Set TargetRange = MasterWorkbook.ActiveSheet.Range("b1:b394")
' Copy cell values one at a time from the source range to the target range.
For Row = 1 To 394
TargetRange.Cells(Row, 1).Value = SourceRange.Cells(Row, 1).Value
Next
ActiveWorkbook.Close
' Set background colour of target range.
TargetRange.Select
With Selection.Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
' Tell Excel to recalculate only those formulas which use the target values.
TargetRange.Dirty
End If
End Sub
For those interested in this code :
User selects a file from nominated directory then selects the nominated range "c1:c394" from that file and pasts it into the "sheet1".
Bypassing clipboard and updates any formulas affected by the added values.