简体   繁体   中英

Dynamic reference of Sheets from a cell - VBA

I'm not sure if this is possible, but it's the one thing I haven't found answered accross the web.

I created one template workbook Schedule.xls that will be filled out by different people, say personA , personB and personC . I need to extract the same range from each workbook by copying it and pasting it into a master file Master.xls , so that I can get the information from each person into this masterbook.

This Master.xls will have as much sheets as persons filling Schedule.xls .

For example, let's stay with those 3 persons: personA , personB and personC .

Once they generate their schedule, I want to get that information and copy it into Master.xls , but in separate sheets named personA , personB and personC .

I want to do this by setting a cell in Schedule.xls , say A1 , where people can choose a value between personA , personB and personC .

This way I can create a dynamic reference for the sheet in Master.xls . in which the macro will paste the info.

`Range("B2.D5").Select
Selection.Copy
Workbooks.Open Filename:= _
    "C:\My Documents\Master.xlsx"
Sheets(*REFERENCE*).Select
Range("B2").Select
ActiveSheet.Paste
Range("A1").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
ActiveWorkbook.Close`

What should I write instead of REFERENCE to set the sheet I want to write on?

Thanks in advance.

I'll suggest a simple, no-code approach. Then, I'll give you some VBA code for your specific request.

Place two workbooks, Carl's SlaveWB.xlsx and your Master.slxm, in the same folder for simplicity. Open the worksheet you want to sync (1-way copy) in both spreadsheets. Create these sheets manually for this simple example. Now, click in cell A1 in the master sheet. While in edit mode, type "=" then click in cell A1 in Carl's worksheet (in the other workbook). Your sheets are now linked. You can do this not just for A1 but the entire worksheet -- just copy/paste cell A1 to the entire worksheet. Now, Carl can take his workboook on the road. Here is how he check's in. He simply copies his latest workbook into your predesignated folder. When you open your master workbook, it will automatically pull in all the data from Carl's "checked-in" workbook.

If you prefer to copy from one workbook to another (to capture formatting), it is not difficult.

First, rename or delete the old "Carl" worksheet in master. Here is code for deleting a worksheet by name. If the name of the sheet in the master is stored in Carl's "Sheet1" worksheet, cell A1, you can pass this as the value of WSName: Workbooks("SlaveWB").Sheets("Sheet1").Cells(1,1).Value.

'DeleteWorksheet(WSName)
Public Function DeleteWorksheet(WSName As String)
    'If Not IIf(IsNull(DebugMode), False, DebugMode) Then On Error GoTo FoundError
    If Not Range("DebugMode").Value Then On Error Resume Next

    Dim WorksheetExists As Boolean
    DeleteWorksheet = False

    'if no worksheet name provided, abort
        If Len(WSName) < 1 Then Exit Function

    'if worksheet exists, delete
        WorksheetExists = False
        On Error Resume Next
        WorksheetExists = (Sheets(WSName).Name <> "") 'if worksheet exists, set WorksheetExists = True
        On Error GoTo FoundError
        If WorksheetExists Then Sheets(WSName).Delete 'if worksheet exists, delete
        DeleteWorksheet = True  'function succeeded (deleted worksheet if it existed)

    Exit Function
FoundError:
    On Error Resume Next
    DeleteWorksheet = False
    Debug.Print "Error: DeleteWorksheet(" & WSName & ") failed to delete worksheet.  "
End Function

Next, copy the revised worksheet from Carl's workbook to the master. The code below copies a worksheet from srcWBName to tgtWBName and names the sheet whatever you like in tgtWBName. I reocmmend you keep the code only only in the master spreadsheet. It is too risky to put the same code in every copy held by every user. And, it will be hard to manage code updates.

Sub CopyWSBetweenWBs(srcWBName As String, srcWSName As String, _
                  tgtWBName As String, tgtWSName As String)

    'srcWBName - name of PersonA's workbook
    'srcWSName - name of worksheet to copy from Person A's workbook
    'tgtWBName - target workbook, the master
    'tgtWSName - what you want to call the worksheet after copying it to the target/master.
    '            If you want this sheetname to be taken from a cell, just pass the cell
    '            reference.  For example, this can be
    '            Workbooks(srcWBName).Sheets(srcWSName).Cells(1,1).Value

    Dim srcWB As Workbook
    Dim srcWS As Worksheet
    Dim tgtWB As Workbook
    Dim tgtWS As Worksheet

    'Create XL objects
    Set srcWB = Workbooks(srcWBName)
    Set srcWS = srcWB.Worksheets(srcWSName)

    Set tgtWB = Workbooks(tgtWBName)
    Set tgtWS = tgtWB.Worksheets(tgtWSName)

    ' Start at the source
    srcWB.Activate
    srcWS.Activate

    ' Copy to target workbook
    srcWS.Copy Before:=tgtWB.Sheets(1) '<~~ copy to beginning of workbook
    ' After copying the worksheet, it is active, so you can rename it now.
    ActiveSheet.Name = tgtWSName


End Sub

That's it. I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM