+ Reply to Thread
Results 1 to 35 of 35

Select only certain columns from closed workbook

Hybrid View

  1. #1
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Select only certain columns from closed workbook

    Hi Gurus,
    Wondering if somebody might be able to assist.

    I am currently running the below code to pull data into a spreadsheet from a (dynamic) closed workbook. It is working as it should but i am hopeful that you may have a solution to only pull in certain columns. ie, if the closed workbook has 90 plus columns of data, and I only need column 2, 5, 8 and 17, then only pull those columns in.
    Any help would be much appreciated as this appears to be a very resource hungry process!

    Function GetValue(path, file, sheet, ref)
    '   Retrieves a value from a closed workbook
        Dim arg As String
    '   Make sure the file exists
        If Right(path, 1) <> "\" Then path = path & "\"
        If Dir(path & file) = "" Then
            GetValue = "File Not Found"
            Exit Function
        End If
    '   Create the argument
        arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
          Range(ref).Range("A1").Address(, , xlR1C1)
    '   Execute an XLM macro
        GetValue = ExecuteExcel4Macro(arg)
    End Function
    
    Sub Module13()
        Dim Month As String
        Quarter = Range("A298").Value
        p = "S:\SampleData\ThisWorkbook\Excel\" & Quarter & ""
        f = "ExcelForum.xls"
        S = "Data1"
        Application.ScreenUpdating = False
        For r = 207 To 296
            For c = 3 To 96
                a = Cells(r, c).Address
                Cells(r, c) = GetValue(p, f, S, a)
            Next c
        Next r
        Application.ScreenUpdating = True
    End Sub
    Thanks in advance,
    Regards,
    Goldfield

  2. #2
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello goldfield,

    This might be a case where ADO and SQL would work. But I cannot say for certain without seeing the data layout. Can you post a copy of the "closed" workbook?
    Sincerely,
    Leith Ross

    Remember To Do the Following....

    1. Use code tags. Place [CODE] before the first line of code and [/CODE] after the last line of code.
    2. Thank those who have helped you by clicking the Star below the post.
    3. Please mark your post [SOLVED] if it has been answered satisfactorily.


    Old Scottish Proverb...
    Luathaid gu deanamh maille! (Rushing causes delays!)

  3. #3
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,
    Thanks for the quick response.
    Example attached.
    Cheers.
    Attached Files Attached Files

  4. #4
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    Thanks for posting the workbook. Do you have headers in row 1?

  5. #5
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,

    Yes I do, but i removed them for confidentiality

  6. #6
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,608

    Re: Select only certain columns from closed workbook

    This is a use of ExecuteExcel4Macro method all the way, so order should be accurate.
    Sub test()
        Dim fn As String, myDir As String, wsName As String, myFile As String
        Dim i As Long, ii As Long, x, y, a, e, myCols
        fn = Application.GetOpenFilename("ExcelFiles,*.xls*")
        If fn = "False" Then Exit Sub
        myDir = Left$(fn, InStrRev(fn, "\"))
        fn = Mid$(fn, InStrRev(fn, "\") + 1)
        wsName = "Data1"
        myFile = "'" & myDir & "[" & fn & "]" & wsName & "'!"
        x = ExecuteExcel4Macro("iferror(match(10^10," & myFile & "c1:c1,1),0)")
        y = ExecuteExcel4Macro("iferror(match(""""," & myFile & "c1:c1,-1),0)")
        x = Application.Max(x, y)
        ReDim a(1 To x, 1 To 4)
        myCols = Array(2, 5, 8, 17)
        For i = 1 To x
            For ii = 0 To UBound(myCols)
                a(i, ii + 1) = ExecuteExcel4Macro(myFile & "r" & i & "c" & myCols(ii))
        Next ii, i
        Cells(1).Resize(x, 4).Value = a
    End Sub

  7. #7
    Forum Expert
    Join Date
    10-06-2008
    Location
    Canada
    MS-Off Ver
    2007 / 2013
    Posts
    5,548

    Re: Select only certain columns from closed workbook

    Sub Maybe()
    Application.ScreenUpdating = False
        With Workbooks.Open("C:\Test\Test.xlsm")    '<------ Change to Path and Workbook Name to be copied FROM
            'In the following line, change the references as required. Sheet to copy FROM and Sheet and Cell to copy INTO
            .Sheets("Sheet2").Range("B:B,E:E,H:H, Q:Q").Copy ThisWorkbook.Sheets("Sheet1").Range("A1")
        End With
    ActiveWorkbook.Close False
    Application.ScreenUpdating = True
    End Sub

  8. #8
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,608

    Re: Select only certain columns from closed workbook

    ADO
    Output in ascending order by 1st column.
    Sub testADO()
        Dim fn As String, cn As Object, rs As Object
        Const wsName As String = "Data1"
        fn = Application.GetOpenFilename("ExcelFiles,*.xls*")
        If fn = "" Then Exit Sub
        Set cn = CreateObject("ADODB.Connection")
        Set rs = CreateObject("ADODB.Recordset")
        With cn
            .Provider = "Microsoft.ACE.OLEDB.12.0"
            .Properties("Extended Properties") = "Excel 12.0;HDR=No;"
            .Open fn
        End With
        rs.Open "Select F2, F5, F8, F14 From `" & wsName & "$A2:T50000` Where F1 Is Not Null Order By F1;", cn
        Cells(1).CopyFromRecordset rs
        Set cn = Nothing: Set rs = Nothing
    End Sub

  9. #9
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    Jindon's solution was close. Here is the working macro. I have installed it in the attached workbook. The results are returned to a second worksheet named "Results".

    Sub ADOCopy()
    
        Dim fn As String, cn As Object, rs As Object
        Dim dstWks As Worksheet, srcWks As Worksheet
        
            Set srcWks = ThisWorkbook.Worksheets("Data1")
            Set dstWks = ThisWorkbook.Worksheets("Results")
            
            Set cn = CreateObject("ADODB.Connection")
            Set rs = CreateObject("ADODB.Recordset")
            
            With cn
                .Provider = "Microsoft.ACE.OLEDB.12.0"
                .Properties("Extended Properties") = "Excel 12.0;HDR=No;"
                .Open ThisWorkbook.FullName
            End With
        
            dstWks.UsedRange.ClearContents
            rs.Open "Select F2, F5, F8, F14 From [" & srcWks.Name & "$] Where F1 Is Not Null Order By F1;", cn
                For n = 0 To rs.Fields.Count - 1
                    dstWks.Cells(1, n + 1).Value = rs.Fields(n).Name
                Next n
            dstWks.Range("A2").CopyFromRecordset rs
        
            Set cn = Nothing: Set rs = Nothing
        
    End Sub
    Attached Files Attached Files

  10. #10
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,
    That looks great- thanks! Just wondering if this would also work with data from a closed workbook (without opening them) and what the code might look like. There are a number of sheets that have macros to pull data from different closed workbooks.
    Cheers,
    Goldfield

  11. #11
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    This will work with closed workbooks. Are you planning to pull data from workbooks in a single folder? If so, are the files names similar?

  12. #12
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hey Leith- yes, they will be from a single (dynamic) folder path, with different workbook numbers in the folder. The folder path will change depending on the financial quarter and referenced by a cell (A298) in the spreadsheet- shown in code from initial message:

    Quarter = Range("A298").Value

    Hope this makes sense.

  13. #13
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    Will you choose the quarter?

    Do the workbooks have more than a single worksheet?

    Will the data from each workbook be added below the previous data in the opened workbook?

  14. #14
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,

    Yes- the quarter (cell A298) is auto-populated from a different sheet on the destination workbook. The destination workbook has multiple worksheets (with different macros on each sheet to pull relevant data).
    The Source workbooks all contain 3 worksheets (Index, data1, Inquiries) but the data will always be on the sheet called "data1". Nothing is required from the Index or Inquiries sheets.
    The data can over write the previous data from column 2 onwards. Column 1 is required for index match purposes. Really appreciate your help on this and I understand it makes it very difficult not having an accurate example to look at!

  15. #15
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    I feel like Alice falling down the rabbit hole.

    What is the date format for Range("A298") ?

    Is the data in the closed workbooks arranged the same as the posted workbook, including number formats?

    The data can over write the previous data from column 2 onwards. Column 1 is required for index match purposes.
    Which worksheet are you referring to?
    Can you post an example of what this looks like because it does not seem to match up with the workbook you posted.

  16. #16
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,

    Sorry for any confusion. Please ignore the comment around the index match- I can sort that out at a later date, the main priority is getting the data.
    To add to the confusion though...there is a formula in cell A298 = TEXT(C298,"mmmyy") which equals "Jun19".

    Data and number formats are the same in both workbooks.

    I will attempt to put together a dummy example.

    Cheers

  17. #17
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    Thanks for the additional information and putting together a sample fro me. I want to be sure about the quarterly date. It is located in the open workbook, the one running the macro, correct?

  18. #18
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,

    Yes, the date is in the open workbook (Goldfield Copy).
    Please see examples attached. I saved the "Source Sheet" in P:Path1\Path2\Jun19 and adjusted the macro on the destination sheet (Goldfield Copy workbook) to look there.
    Hope this makes more sense!
    Cheers
    Attached Files Attached Files

  19. #19
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    Thanks for the files. That made this much easier and hopefully accurate.

    The macro below will search the folder path for a workbook with the name " 'Quarter' Source Sheet.xls" where 'Quarter' is the contents of cell A298 of the Destination Sheet. The column "D,F,J" in the closed workbook will be returned to the Destination Sheet in columns "B,C,D". Previous data is deleted on the destination sheet each time the macro runs.

    NOTE: Change the variable Path to folder where you files are located.

    Sub PullQuarterlyData()
    
        Dim char As String, cols As Variant, fields As Variant
        Dim fn As String, cn As Object, rs As Object
        Dim Headers As String, Item As Variant, Path As Variant
        Dim dstWks As Worksheet, dstRng As Range, Rng As Range
        Dim srcFile As String, srcWkb As String, srcWks As String
        
        Const adOpenForwardOnly     As Long = 0
        Const adLockReadOnly        As Long = 1
        Const adCmdText             As Long = 1
        
            cols = "D,F,J"
            
            Set dstWks = ThisWorkbook.Worksheets("Destination Sheet")
            Set dstRng = dstWks.Range("A2")
            
            Path = "P:\Path1\Path2\"
            
            srcWkb = "Source Sheet.xls"
            srcWks = "Data1"
            srcFile = Path & dstWks.Range("A298") & " " & srcWkb
            
                If Dir(srcFile) = "" Then
                    MsgBox "The workbook '" & srcWkb & "' was Not Found in the folder: " & vbLf & Path, vbCritical
                    Exit Sub
                End If
            
                Set Rng = dstRng
                
                For Each Item In Split(cols, ",")
                    fields = fields & char & "F" & dstWks.Cells(1, Item).Column - 1
                    Set Rng = Rng.Offset(0, 1)
                    char = ","
                Next Item
                
                Set Rng = dstRng.CurrentRegion
                Set Rng = Intersect(Rng, Rng.Offset(1, 1))
                    Rng.ClearContents
                        
                Set cn = CreateObject("ADODB.Connection")
                Set rs = CreateObject("ADODB.Recordset")
            
                With cn
                    .Provider = "Microsoft.ACE.OLEDB.12.0"
                    .Properties("Extended Properties") = "Excel 12.0;HDR=No;"
                    .Open srcFile
                End With
            
                rs.Open "Select " & fields & " From [" & srcWks & "$] Where F1 Is Not Null Order By F1;", cn, adOpenForwardOnly, adLockReadOnly, adCmdText
                dstRng.Offset(0, 1).CopyFromRecordset rs
            
            cn.Close
            Set cn = Nothing: Set rs = Nothing
        
    End Sub

  20. #20
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,

    Thanks for your persistence- it is much appreciated!
    I think we are very close but i am getting "The workbook 'Source Sheet.xls' was not found in the folder:" error message. I have checked the file path to make sure that it is looking in the right spot but i can't put my finger on why it can't find it? I have tried changing directories and paths etc to no avail.

    Pretty sure I have work it out now- a few tweaks here and there should get it sorted.

    Thanks again for your help!

    Cheers,
    Goldfield
    Last edited by goldfield; 10-24-2019 at 02:26 AM.

  21. #21
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    Sorry I didn't get back to you yesterday. The only possible explanation I have is the path was incorrect. The quarter was added as a prefix to the file name. Is that correct or was the quarter a separate folder?

  22. #22
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,
    The quarter is a separate folder ie P:\Path1\path2\Jun19(A298)\SourceSheet.xls, that was the issue.
    Sorry if I didn't explain it clearly earlier. I then got an error with dstRng.CurrentRegion not defined, and rng.clrcontents
    I managed to get it working in the sample, but have not been able to get it working in the live data as yet.
    Regards,
    Goldfield

  23. #23
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    What issues are you having with the live data?

  24. #24
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49
    Quote Originally Posted by Leith Ross View Post
    Hello Goldfield,

    What issues are you having with the live data?
    At the moment i can't get it to find the file. In the live version there are 5 folders, the 4th being the dynamic quarter, then the file name. The file name is numeric which i wouldn't have thought would make a difference? E.g. 1234567. xls

  25. #25
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    All file names are treated as strings. The same does not hold true for folders depending on the method of retrieval.

    Are you getting any error messages? If so, what are they?

  26. #26
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    I'm getting "The workbook '1234567.xls' was not found in the folder:P:\Path1\Path2\Path3\Path4\Jun19

  27. #27
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Golfield,

    Did you add the file separator "\" to the end of the string?

        P:\Path1\Path2\Path3\Path4\Jun19\

  28. #28
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,
    I have now tweaked the code so it works in the live data (see attached). I now need to copy the macro (changing destination and source paths) into a number of other sheets in the same workbook. When I do that, I get a subscript out of range error (also attached). Can you please point me in the direction of where I might be going wrong, and the correct way to go about this?
    Cheers,
    Goldfield

    Sub PullQuarterlyData87520034()
    
        Dim char As String, cols As Variant, fields As Variant
    
        Dim fn As String, cn As Object, rs As Object
    
        Dim Headers As String, Item As Variant, Path As Variant
    
        Dim dstWks As Worksheet, dstRng As Range, Rng As Range
    
        Dim srcFile As String, srcWkb As String, srcWks As String
    
       
    
        Const adOpenForwardOnly     As Long = 0
    
        Const adLockReadOnly        As Long = 1
    
        Const adCmdText             As Long = 1
    
       
    
            cols = "C,O,AA,AM,AY,BK,BW,CI"
    
           
    
            Set dstWks = ThisWorkbook.Worksheets("87520034")
    
            Set dstRng = dstWks.Range("A1")
    
           
    
            Path = "S:\OUTGRP\8752\Embargoed_Data\Excel\" & dstWks.Range("A297") & "" & "\"
    
           
    
            srcWkb = "87520034.xls"
    
            srcWks = "Data1"
    
            srcFile = Path & srcWkb
    
           
    
                If Dir(srcFile) = "" Then
    
                    MsgBox "The workbook '" & srcWkb & "' was Not Found in the folder: " & vbLf & Path, vbCritical
    
                    Exit Sub
    
                End If
    
           
    
                Set Rng = dstRng
    
               
    
                For Each Item In Split(cols, ",")
    
                    fields = fields & char & "F" & dstWks.Cells(1, Item).Column
    
                    Set Rng = Rng.Offset(0, 1)
    
                    char = ","
    
                Next Item
    
               
    
           
    
               
    
                Set Rng = dstRng.Offset(0, 1)
    
                Set Rng = Intersect(Rng, Rng.Offset(1, 1))
    
                   
    
                 
    
                Set cn = CreateObject("ADODB.Connection")
    
                Set rs = CreateObject("ADODB.Recordset")
    
           
    
                With cn
    
                    .Provider = "Microsoft.ACE.OLEDB.12.0"
    
                    .Properties("Extended Properties") = "Excel 12.0;HDR=No;"
    
                    .Open srcFile
    
                End With
    
           
    
                rs.Open "Select " & fields & " From [" & srcWks & "$] ;", cn, adOpenForwardOnly, adLockReadOnly, adCmdText
    
                dstRng.Offset(0, 1).CopyFromRecordset rs
    
           
    
            cn.Close
    
            Set cn = Nothing: Set rs = Nothing
    
            Range("$B$11:$I$295").Select
    
    With Selection
    
    Selection.NumberFormat = "General"
    
    .Value = .Value
    
    Range("$C$303").Select
    
    End With
    
       
    
    End Sub
    Attached Images Attached Images

  29. #29
    Forum Expert
    Join Date
    10-06-2008
    Location
    Canada
    MS-Off Ver
    2007 / 2013
    Posts
    5,548

    Re: Select only certain columns from closed workbook

    It's late here in this part of the world. Leith might be having his beauty sleep already.
    In the meantime a possibility that might cause your message.

    Subscript out of range indicates that you've tried to access an element from a collection that doesn't exist. Is there a sheet "87520034" in your workbook?
    No leading or trailing spaces in it's name?


    And also, change this
    Range("$B$11:$I$295").Select
    With Selection
    Selection.NumberFormat = "General"
    .Value = .Value
    Range("$C$303").Select 
    End With
    to this
    With Range("B11:I295")
         .NumberFormat = "General"
        .Value = .Value
    End With
    Range("$C$303").Select    '<---- Is this required? If not, leave it out.

  30. #30
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Jolivanes,
    Yes, the sheet "87520034" does exist. Actually- the code for the "87520034" sheet is fine, it's when I copied this to the sheet "87520033" and changed the two lines of code below that I had the issue :
    Set dstWks = ThisWorkbook.Worksheets("87520033")
    srcWkb = "87520033.xls"
    I made sure there were no spaces etc. Thanks for the heads up on the other piece of code as well.
    Cheers

    EDIT: Sorry! I think I have been looking at this for too long...completely missed something in the file path. That is now fixed.
    Now getting the below error:
    Run-time error'-2147217904(80040e10)':
    No value given for one or more required parameters
    in this line
    rs.Open "Select " & fields & " From [" & srcWks & "$] ;", cn, adOpenForwardOnly, adLockReadOnly, adCmdText
    
                dstRng.Offset(0, 1).CopyFromRecordset rs
    Last edited by goldfield; 10-25-2019 at 03:04 AM.

  31. #31
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    With the changes you made and only showing snippets of the revised code, I am not sure what is going on now. Can you post the macro code you have that is most current?

  32. #32
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,

    Current Code attached:
    Sub PullQuarterlyData87520034()
    
        Dim char As String, cols As Variant, fields As Variant
    
        Dim fn As String, cn As Object, rs As Object
    
        Dim Headers As String, Item As Variant, Path As Variant
    
        Dim dstWks As Worksheet, dstRng As Range, Rng As Range
    
        Dim srcFile As String, srcWkb As String, srcWks As String
    
       
    
        Const adOpenForwardOnly     As Long = 0
    
        Const adLockReadOnly        As Long = 1
    
        Const adCmdText             As Long = 1
    
       
    
            cols = "C,O,AA,AM,AY,BK,BW,CI"
    
           
    
            Set dstWks = ThisWorkbook.Worksheets("87520034")
    
            Set dstRng = dstWks.Range("A1")
    
           
    
            Path = "S:\OUTGRP\8752\Embargoed_Data\Excel\" & dstWks.Range("A297") & "" & "\"
    
           
    
            srcWkb = "87520034.xls"
    
            srcWks = "Data1"
    
            srcFile = Path & srcWkb
    
           
    
                If Dir(srcFile) = "" Then
    
                    MsgBox "The workbook '" & srcWkb & "' was Not Found in the folder: " & vbLf & Path, vbCritical
    
                    Exit Sub
    
                End If
    
           
    
                Set Rng = dstRng
    
               
    
                For Each Item In Split(cols, ",")
    
                    fields = fields & char & "F" & dstWks.Cells(1, Item).Column
    
                    Set Rng = Rng.Offset(0, 1)
    
                    char = ","
    
                Next Item
    
               
    
           
    
               
    
                Set Rng = dstRng.Offset(0, 1)
    
                Set Rng = Intersect(Rng, Rng.Offset(1, 1))
    
                   
    
                 
    
                Set cn = CreateObject("ADODB.Connection")
    
                Set rs = CreateObject("ADODB.Recordset")
    
           
    
                With cn
    
                    .Provider = "Microsoft.ACE.OLEDB.12.0"
    
                    .Properties("Extended Properties") = "Excel 12.0;HDR=No;"
    
                    .Open srcFile
    
                End With
    
           
    
                rs.Open "Select " & fields & " From [" & srcWks & "$] ;", cn, adOpenForwardOnly, adLockReadOnly, adCmdText
    
                dstRng.Offset(0, 1).CopyFromRecordset rs
    
           
    
            cn.Close
    
            Set cn = Nothing: Set rs = Nothing
    
            .Select
    
    With Range("B11:I295")
         .NumberFormat = "General"
        .Value = .Value
    End With
    
    
    
       
    
    End Sub

  33. #33
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    I have added a little more error checking. Hopefully, this will help us. In the Path you were using A297. Seem to be a error so I changed it to A298.

    Sub PullQuarterlyData87520034()
    
        Dim char As String, cols As Variant, fields As Variant
        Dim fn As String, cn As Object, rs As Object
        Dim Headers As String, Item As Variant, Path As Variant
        Dim dstWks As Worksheet, dstRng As Range, Rng As Range
        Dim srcFile As String, srcWkb As String, srcWks As String
    
        Const adOpenForwardOnly     As Long = 0
        Const adLockReadOnly        As Long = 1
        Const adCmdText             As Long = 1
            
            cols = "C,O,AA,AM,AY,BK,BW,CI"
            
            Set dstWks = ThisWorkbook.Worksheets("87520034")
            Set dstRng = dstWks.Range("A1")
            
            Path = "S:\OUTGRP\8752\Embargoed_Data\Excel\" & dstWks.Range("A298")
            Path = IIf(Right(Path, 1) <> "\", Path & "\", Path)
                
            srcWkb = "87520034.xls"
            srcWks = "Data1"
            srcFile = Path & srcWkb
    
                If Dir(Path, vbDirectory) = "" Then
                    MsgBox "The folder '" & Path & "' was Not Found.", vbCritical
                    Exit Sub
                End If
                
                If Dir(srcFile) = "" Then
                    MsgBox "The workbook '" & srcWkb & "' was Not Found in the folder: " & vbLf & Path, vbCritical
                    Exit Sub
                End If
    
                Set Rng = dstRng
    
                For Each Item In Split(cols, ",")
                    fields = fields & char & "F" & dstWks.Cells(1, Item).Column
                    Set Rng = Rng.Offset(0, 1)
                    char = ","
                Next Item
    
                Set Rng = dstRng.Offset(0, 1)
                Set Rng = Intersect(Rng, Rng.Offset(1, 1))
    
                Set cn = CreateObject("ADODB.Connection")
                Set rs = CreateObject("ADODB.Recordset")
    
                With cn
                    .Provider = "Microsoft.ACE.OLEDB.12.0"
                    .Properties("Extended Properties") = "Excel 12.0;HDR=No;"
                    .Open srcFile
                End With
                
                rs.Open "Select " & fields & " From [" & srcWks & "$] ;", cn, adOpenForwardOnly, adLockReadOnly, adCmdText
                dstRng.Offset(0, 1).CopyFromRecordset rs
    
            cn.Close
            Set cn = Nothing: Set rs = Nothing
    
        With Range("B11:I295")
            .NumberFormat = "General"
            .Formula = .Value
        End With
    
    End Sub

  34. #34
    Registered User
    Join Date
    10-31-2012
    Location
    South Australia, Australia
    MS-Off Ver
    Excel 2016
    Posts
    49

    Re: Select only certain columns from closed workbook

    Hi Leith,
    Thanks for the updated code. This works fine in the first spreadsheet but when I copy this code to the next spreadsheet (changing the destination and source path), I get the below error:
    Run-time error'-2147217904(80040e10)':
    No value given for one or more required parameters
    in this line of code:
    rs.Open "Select " & fields & " From [" & srcWks & "$] ;", cn, adOpenForwardOnly, adLockReadOnly, adCmdText
    Can you please advise what this code does and where it might be falling over?
    Cheers,
    Goldfield


    please ignore- this occurred as the source worksheet columns didn't exist.
    Last edited by goldfield; 10-27-2019 at 07:06 PM. Reason: resolved

  35. #35
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258

    Re: Select only certain columns from closed workbook

    Hello Goldfield,

    That line creates the ADO Record Set based on the SQL Query string. When you have problems or have made changes to the code, please post the code. I hate trying to second guess what people have done.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Copy specific columns from closed workbook, paste as values
    By marcosis in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 09-26-2018, 07:30 AM
  2. [SOLVED] Copy Select Columns from closed workbook into active workbook
    By 3345james in forum Excel Programming / VBA / Macros
    Replies: 9
    Last Post: 10-09-2015, 02:04 PM
  3. Replies: 0
    Last Post: 03-27-2014, 12:38 PM
  4. Macro to open a closed workbook and select copy cells into an open workbook
    By helloganesh in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 02-10-2013, 02:00 PM
  5. Copy columns from closed workbook to different columns in open workbook
    By jGLZa in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 01-04-2012, 11:03 PM
  6. Replies: 18
    Last Post: 12-13-2011, 10:15 AM
  7. Copy successive columns to a closed workbook
    By RedWing in forum Excel Programming / VBA / Macros
    Replies: 15
    Last Post: 09-08-2011, 04:38 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1