views:

157

answers:

2

My question is as follows: I have given a workbook to multiple people. They have this workbook in a folder of their choice. The workbook name is the same for all people, but folder locations vary. Let's assume the common file name is MyData-1.xls. Now I have updated the workbook and want to give it to these people. However when they receive the new one (let's call it MyData-2.xls) I want specific parts of their data pulled from their file (MyData-1) and automatically put into the new one provided (MyData-2). The columns and cells to be copied/imported are identical for both workbooks. Let's assume I want to import cell data (values only) from MyData-1.xls, Sheet 1, cells B8 through C25 ... to ... the same location in the MyData-2.xls workbook. How can I specify in code (possibly attached to a macro driven import data now button) that I want this data brought into this new workbook. I have tried it at my own location by opening the two workbooks and using the copy/paste-special with links process. It works really well, but It seems to create a hard link between the two physical workbooks. I changed the name of the source workbook and it still worked. This makes me believe that there is a "hard link" between the tow and that this will not allow me to give the target (MyData-2.xls) workbook to others and have it find their source workbook.

A: 

You should use the copy/paste-special for values only:

Private Sub ImportData_Click()

  On Error GoTo OpenTheSheet

    Workbooks("MyData-1.xls").Activate
    GoTo SheetOpen

  OpenTheSheet:
    Workbooks.Open "MyData-1.xls"
    Workbooks("MyData-1.xls").Activate

  SheetOpen:
    On Error GoTo 0
    Workbooks("MyData-1.xls").Worksheets("sheetwhatever").firstRange.Copy
    Workbooks("MyData-2.xls").Worksheets("anothersheet").yourRange.PasteSpecial(xlPasteValues)

End Sub

This could be cleaned up a bit, but it's always messy to do file stuff in VBA, I'd probably put the opening code in a function. Make sure they put the new file in the same directory as the old file.

Lance Roberts
thx for answer: However I'm not cnocerned with the pasting special thing. I am concerned that their workbooks which have not been part of my test (and my now, linked workbooks) will not work. If I passed on my target workbook to them, would it find their MyData-1 workbook and suck the data from it into the one I send them?
Allan
I'm confused about why you're linking them, that seems to be the problem. I would think you'd give them MyData-2.xls and they would hit a button in it and it would draw in the values specified from their old MyData-1.xls. Why do you need linking?
Lance Roberts
I edited my answer to show the basics, let me know if you need something different.
Lance Roberts
Thanks Lance... Yes I don't need linking.. The only reason I have them "linked" is because I currently don't have the code required to draw the data from the MyData-1 workbook. I simply did a test by opening both and did a copy/paste special/values (with the paste link option).
Allan
Also...will the MyData-2 (target) workbook import the data even if the source workbook is closed?
Allan
Good Point, I'll edit in some code for that.
Lance Roberts
Thanks a lot Lance. I'll give it a test over the weekend. Looks great. I'll let you know how it goes. Best regards .. Allan
Allan
Lance..I tried the code ant it cannot find the file MyData-1.xls. The file 'does' exist and is in the same directory as MyData-2. Any suggestions?
Allan
@Allan, I'll work on it monday, we may need to add some kind of relative path statement.
Lance Roberts
Excellent ... Thank you Lance
Allan
@Allan, I edited to a copy that I've tested on my machine, just make sure both workbooks are in the same directory.
Lance Roberts
Thanks Lance I'll give it a try.
Allan
A: 

To clarify my understanding, each user has a spreadsheet called MyData-1.xls but with varying locations. You would like to send each person a new spreadsheet MyData-2 which will automatically pull in data from range B8:C25 in MyData-1.xls?

There are various options on doing this and below I have provided one way of doing this. In short, the user will open MyData-2, click a button, and the code will search for MyData-1 on their directory, open the workbook, grab the data, paste it into MyData-2, and then close MyData-1.

Sub UpdateWorkbook()

'Identify workbook you would like to pull data from (same for all users)
    Dim TargetWorkbook As String
    TargetWorkbook = "MyData-1"

'Get the full path of that workbook by searching in a specified directory
    Dim TargetPathName As String
    TargetPathName = GetFilePath(TargetWorkbook)

'Retrieve data in range B8:C25, copy and paste, then close workbook

    Dim TargetRng As Range
    Application.ScreenUpdating = False
    Workbooks.Open Filename:=TargetPathName
    Set TargetRng = Sheets("Sheet1").Range("B8:C25")
    TargetRng.Copy Destination:=ThisWorkbook.Worksheets(1).Range("B8:C25")
    ActiveWorkbook.Close
    Application.ScreenUpdating = True

End Sub

Function GetFilePath(TargetWkbook As String) As String

    Dim FullFilePath As String

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.EnableEvents = False

    On Error Resume Next
        With Application.FileSearch
            .NewSearch
            .LookIn = "C:\"
            .FileType = msoFileTypeExcelWorkbooks
            .SearchSubFolders = True
            .Filename = TargetWkbook
                If .Execute > 0 Then
                    FullFilePath = .FoundFiles(1)
                End If
        End With

    GetFilePath = FullFilePath

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.EnableEvents = True

End Function

By way of explanation:

  1. In the sub you first need to specify the name of the workbook MyData-1
  2. The Function GetFilePath will then get the full path name of the workbbok. Note that I have set it to look in the "C:\" drive and you may want to amend that
  3. Once we have the full file path we can easily open the workbook and copy the required range.

Note that the screenupdating is turned off to create the 'illusion' that the workbook has not been opened when the data is copied. Also, I have added a button on the worksheet of MyData-2 to trigger the code i.e. user opens workbook, presses button, and data is imported.

Finally, this code could be augmented significantly and you may want to tweak it. For example, error checking if file not found, searching in multiple directories (e.g C:\, D:)...

Hope this gets you started on the right track

Remnant
Remnant, Thank you very much for your help. I will give this a try too over the weekend. Will post soon and report how I went. The help I have received on this post is incredible. Thank you all for your time and effort.
Allan
To clarify my understanding, each user has a spreadsheet called MyData-1.xls but with varying locations. You would like to send each person a new spreadsheet MyData-2 which will automatically pull in data from range B8:C25 in MyData-1.xls? .... ((( Yes this is correct.))) ... thanks
Allan
@Allan - Give it a whirl and let me know how it works out for you. Glad to help.
Remnant
Remnant: I get a 1004 error on the line (listed below) when running the macro. Line 11 in your above code....... Workbooks.Open Filename:=TargetPathName ......
Allan
I also notice that that filetype in explorer says MicroSoft Excel Worksheet as apposed to Woorbook ....Does this possible cause the error because I note you have referrer to the filetype as a "workbook". (?)
Allan
ok Remnant: I moved both files into C;| root directory. And it works great. So I still have a bit of a problem as almost none of the users will have the file in this location. When I move then both from c:\ the macro stops on the line mentioned two posts ago. I thuoght that becauseyou had .LookIn = "C:\" that it would look in the whole c: drive (all folders). But it appears to look in the root directory.Now, when I move MyData-2 into another folder ... it still works. So I presume it's fixed on looking in that c:\ directory only. (???) Thanks for you very gracious work...
Allan
@Allan: Updated the code now to ensure it looks through all folders and subfolders within C:\ root. Please let me know how you get on.
Remnant
Remnant: It takes about 10 seconds to look for MyData-1 and find it. I tried putting it in different locations and it found the file perfectly and extracted the data into MyData2. Excellent - Thank you very much.
Allan
I do however have two questions:Q1) If I don't know the drive letters that others have on their PCs, is there a way to add something to the function line .LookIn = "C:\" so that it will look on all hard drives, perhaps beginning with C:\ and working through them in numerical order? I understand you said in earlier text that I could type in more drive letters, however, they could have it on a drive like Z or P.
Allan
Q2) If I want to copy more than one range across such as Range("B8:C25") and Range("B42:C50") ... how can I stack these up without having to duplicate the two lines of code many times? Again, You have given me your time and I'm very grateful. Awesome job.
Allan
By the Way FYI: I moved the file MyData-1 to my external drive I:\ and changed the LookIn = "C:\" to LookIn = "I:\"......it took 4mins and 40 seconds to find the file compared to 10 seconds or so on c:\ drive. But it still found it.
Allan
Remnant: I need to rewrite Q2)..I have realized that I can live with copying a single larger block of info....so no need for multiple blocks now. However I have a new issue: I have two sheets (1) and (2). Sheet 1 has been solved. But I need to also copy and paste a block of data [range A25:D35] from sheet (2) in MyData1 to same sheet (2) and range in MyData2. I tried duplicating some of the code and couldn't get it to work. If you are around sometime, perhaps you could show me if I can add a couple of lines to do this in the code above. Many thanks.
Allan
@Allan. Firstly, looping through all subfolders is time consuming. Assuming your users each keep MyData-1 in the same place (e.g. C:\My Documents and Settings) then it might be an idea to save the user ID and filepath in the MyData-2 worksheet so that it does not have to perform the search every time i.e. use stored filepath in MyData-2 to check for the workbook first as it is unlikely users keep moving MyData-1 to different folders(?).
Remnant
@ Allan - This code copies ranges from different sheets. Please amend code posted above accordingly: Set TargetRng = Worksheets(1).Range("B8:C25") TargetRng.Copy Destination:=ThisWorkbook.Worksheets(1).Range("B8:C25") Set TargetRng = Worksheets(2).Range("B8:C25") TargetRng.Copy Destination:=ThisWorkbook.Worksheets(2).Range("B8:C25")
Remnant
Remnant: The users will only perform this function one time. That is, sucking in the data from MyData-1 to MyData2. Then MyData-2 becomes the current workbook untill the next update (which is about every quarter). I'm not sure that this would change your thinking regarding your "Firstly" response above. I guess it eliminates the need to store the filepath as there will be no future processing. Regarding the copying from different sheets in MyData-1 to same in MyData-2....I'll give it a whirl and let you know. Thanks again for being so patient with a novice excel user. Very grateful.
Allan
?Remnant: I have noticed a problem. With regard to sheet(2). I was actually wanting to copy B8:C25 in MyData-1 to different cells L8:M25 on sheet(2) MyData-2 workbook. This has created a problem as follows. The data comes in a zeros (0s) and there is a link back to MyData-1 workbook in each cell too, instead of just the raw values. Wow! Is this because I am trying to copy the block of values to different columns, even though they are on the same sheet in the newer workbook? It works perfectly when copying the sheet(1) data to exactly the same location. Any suggestions??
Allan
@Allan - Not sure on this as it worked when I tested on my PC. The fact that destination range is different from source range should not make any difference.
Remnant
Remnant> I'll keep working on it. Many thanks ... I'll let you know how I'm going.
Allan
?Remnant: I think I've found out why I have the problem. The cells in sheet(2) of MyData-1 that I want copied already are linked to other cells in the same workbook. So when they are copied they come in as NOT values only. They have a path in the cells. The cells copied from Sheet(1) of MyData-1 are fine as they were never linked to any source. They were just raw numbers. Q: Is there a way we can (for the sheet copy process) put in some code to copy special with values only. I think this would then biring this range with raw numbers only. Thank you.
Allan
More on the above note: I retyped over the "link produced" values on sheet(2) MyData-1 so there was no link present. No surprise...it worked like a dream. Now we definately know what the problem is. (Values in MyData-1 that are bourne from a link need to be copied as a "values only" sort of process. (like paste special I think). Currently the code .... Set TargetRng = Worksheets(2).Range("B8:C25") TargetRng.Copy Destination:=ThisWorkbook.Worksheets(2).Range("B8:C25") .... brings in paths and not values only. Just thought I'd clarify my predicament. Cheers..Allan
Allan
As an ending note to the above problem: When a cell (or range of cells) originate from a link to some other info, they cannot be copied using the above code, especially if the range is to be copied to a range within different columns. The previous links are maintained and the values are incorrect. To overcome this, I wrote some code that went to the source workbook, copied and pasted (special, values only) over the existing values) thus eliminating the link. Then executed the copy command folowed by paste as above. Then close source workbook without saving changes. It worked a treat.!!!
Allan