0
votes

Hi I am new to VBA so apologies if my code looks bad. I have a macro that updates specific cells in one column in a master worksheet, pulling data from a specific workbook. However, I would like my macro to know that I am pulling data from another workbook without specifying workbooks.Open(FileName) so I can automatically update my master sheet from any other open workbook.

The main problem is, since the same data are found in different cells in multiple workbooks, I am wondering how I can copy these data while referring to their different cells for each workbook.

Code:

Sub UpdateData()

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim EMS As Worksheet
Dim TD As Worksheet
Dim JV1 As Worksheet

Application.ScreenUpdating = False

Set wb1 = ThisWorkbook
wb1.Application.Visible = True
Set ws1 = wb1.Sheets(" Master Data")
Set wb2 = Workbooks.Open("C:\Users\HONL120\Desktop\Sept HC Reports\HR Headcount Report 2018 Australia SEPTEMBER.XLSX")
wb2.Application.Visible = False
Set EMS = Sheets("Employee Movement Summary")
EMS.Range("J19").Copy
ws1.Range("J34").PasteSpecial xlPasteValues

Set TD = Sheets("Turnover Dashboard")
TD.Range("J44").Copy
ws1.Range("J2").PasteSpecial xlPasteValues
TD.Range("J47").Copy
ws1.Range("J3").PasteSpecial xlPasteValues

EMS.Range("J10").Copy
ws1.Range("J5").PasteSpecial xlPasteValues
EMS.Range("J11").Copy
ws1.Range("J6").PasteSpecial xlPasteValues
EMS.Range("J16").Copy
ws1.Range("J7").PasteSpecial xlPasteValues
EMS.Range("J17").Copy
ws1.Range("J8").PasteSpecial xlPasteValues

TD.Range("K3:K7").Copy
ws1.Range("J10:J14").PasteSpecial xlPasteValues
TD.Range("J32:J43").Copy
ws1.Range("J16:J27").PasteSpecial xlPasteValues

Set JV1 = Sheets("JV1")
JV1.Range("Q26").Copy
ws1.Range("J29").PasteSpecial xlPasteValues
JV1.Range("Q28:Q29").Copy
ws1.Range("J30:J31").PasteSpecial xlPasteValues

Application.ScreenUpdating = True
wb2.Application.Visible = True
End Sub

So for example, in this other workbook, the range to copy TD.Range("J44").Copy is based on cell J44, but this may not be the case in other workbooks with the same type of data.

Likewise, I would like to copy from another open workbook no matter what is opened, and not specifying a file name as such Set wb2 = Workbooks.Open("C:\Users\HONL120\Desktop\Sept HC Reports\HR Headcount Report 2018 Australia SEPTEMBER.XLSX").

Is there a way to automate this? or must I find the specific cells to copy in each workbook manually? Thanks in advance!

1
Try giving those cells particular names, the same in each workbook. The macro can the just call the data by name.Solar Mike
@SolarMike Could you give me an example? Sorry for being noobish about this.Lim Hong En
Use the insert menu and manage names : give a cell a name and try... You can use the names in calculations as well...Solar Mike

1 Answers

0
votes

I think you are saying you want a reference to the Excel file that you are importing data from, right. Try the code below and see if it does what you need.

Sub Basic_Example_1()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long

    'Fill in the path\folder where the files are
    MyPath = "C:\path_to_your_excel_files\"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next

                With mybook.Worksheets(1)
                    FirstCell = "A2"
                    Set sourceRange = .Range(FirstCell & ":" & RDB_Last(3, .Cells))
                    'Test if the row of the last cell >= then the row of the FirstCell
                    If RDB_Last(1, .Cells) < .Range(FirstCell).Row Then
                         Set sourceRange = Nothing
                    End If
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all columns then skip this file
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "Sorry there are not enough rows in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in column A
                        With sourceRange
                            BaseWks.Cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.Range("B" & rnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

Function RDB_Last(choice As Integer, rng As Range)
'Ron de Bruin, 5 May 2008
' 1 = last row
' 2 = last column
' 3 = last cell
    Dim lrw As Long
    Dim lcol As Integer

    Select Case choice

    Case 1:
        On Error Resume Next
        RDB_Last = rng.Find(What:="*", _
                            after:=rng.Cells(1), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
        On Error GoTo 0

    Case 2:
        On Error Resume Next
        RDB_Last = rng.Find(What:="*", _
                            after:=rng.Cells(1), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByColumns, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Column
        On Error GoTo 0

    Case 3:
        On Error Resume Next
        lrw = rng.Find(What:="*", _
                       after:=rng.Cells(1), _
                       Lookat:=xlPart, _
                       LookIn:=xlFormulas, _
                       SearchOrder:=xlByRows, _
                       SearchDirection:=xlPrevious, _
                       MatchCase:=False).Row
        On Error GoTo 0

        On Error Resume Next
        lcol = rng.Find(What:="*", _
                        after:=rng.Cells(1), _
                        Lookat:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Column
        On Error GoTo 0

        On Error Resume Next
        RDB_Last = rng.Parent.Cells(lrw, lcol).Address(False, False)
        If Err.Number > 0 Then
            RDB_Last = rng.Cells(1).Address(False, False)
            Err.Clear
        End If
        On Error GoTo 0

    End Select
End Function