Results 1 to 34 of 34

Thread: [RESOLVED] Looping through sheets problems and setting of variables - vba

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Resolved [RESOLVED] Looping through sheets problems and setting of variables - vba

    I am doing this simple routine - checking for values that contain prefix IK column A in all sheets except the IK ouput which is the ouput sheet only.

    I am having difficulty setting the varaible in the correct way and getting it to work.

    Please see comments which explains some of the difficulties.

    Can anyone help debug??


    VB Code:
    1. Sub IKlist()
    2.  
    3.  
    4. Dim wksSheet As Worksheet
    5. Dim i As Integer
    6. Dim thiscell As String
    7. Dim Filelength As Integer
    8. Dim obook As Workbook
    9. Dim xlapp As Excel.Application
    10. Dim j As Integer
    11.  
    12. ' CREATE OUTPUT SHEET IK Output
    13.  
    14. 'Count Worksheets
    15. sheetcount = Worksheets.Count
    16.  
    17. 'Add worksheets after the last sheet
    18. Worksheets.Add After:=Sheets(sheetcount)
    19.  
    20. 'Count Worksheets
    21. sheetcount = Worksheets.Count
    22.  
    23. 'Name the sheet and add the number of sheets
    24. Worksheets(sheetcount).Name = "IK output"
    25.  
    26. 'set varaibles to work with the active workbook and any sheet except the ouput sheet
    27.  
    28. Set xlapp = Excel.Application    'work with active excel application
    29. Set obook = xlapp.ActiveWorkbook    'work with active workbook - not specific
    30. Set wksSheet = ??????????????  'set wksheet to be any worksheet in the active workbook. This is because I am looping through each worksheet
    31.  
    32. ' Loop through each worksheet in active workbook - not a specific work book- looking for values that contain prefix IK  and copying it to the IK output sheet
    33.  
    34. ' The output sheet  is the ouput sheet only - therefore we should not loop through this sheet - its only used for poulating results
    35.  
    36.  
    37. Filelength = wksSheet.usedrange.Rows.Count
    38.    j = 1
    39. For Each wksSheet In obook.Worksheets
    40.  
    41.     For i = 1 To Filelength
    42.     thiscell = Cells(i, 1)
    43.     If Left(thiscell, 2) = "IK" Then
    44.     Worksheets("IK output").Cells(j, 1).Value = Cells(i, 1).Value
    45.     End If
    46.     j = j + 1
    47.     Next i
    48. Next wksSheet
    49.  
    50.  
    51.  
    52. End Sub

  2. #2
    Frenzied Member zaza's Avatar
    Join Date
    Apr 2001
    Location
    Borneo Rainforest Habits: Scratching
    Posts
    1,486

    Re: Looping through sheets problems and setting of variables - vba

    A couple of suggestions:

    You can set wksSheet to be Worksheets(1) - there is always a first sheet in any workbook.

    If you move the line: Filelength = wkssheet.usedrange... inside the For loop then it will recalculate this for each sheet, which presumably is what you need....


    zaza
    I use VB 6, VB.Net 2003 and Office 2010



    Code:
    Excel Graphing | Excel Timer | Excel Tips and Tricks | Add controls in Office | Data tables in Excel | Gaussian random number distribution (VB6/VBA,VB.Net) | Coordinates, Vectors and 3D volumes

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    I have made the changes below - it runs for about 2 seconds but then stops. don't think its looping through any of the sheets, whats wrong buddy??
    All its doing at mow is creating the sheet.

    Also the sheet IK ouput gets created previously - its not meant to loop to this sheet - this is the output only.


    VB Code:
    1. Sub IKlist()
    2.  
    3.  
    4. Dim wksSheet As Worksheet
    5. Dim i As Long
    6. Dim thiscell As String
    7. Dim Filelength As Integer
    8. Dim obook As Workbook
    9. Dim xlapp As Excel.Application
    10. Dim j As Long
    11.  
    12. ' CREATE OUTPUT SHEET IK Output
    13.  
    14. 'Count Worksheets
    15. sheetcount = Worksheets.Count
    16.  
    17. 'Add worksheets after the last sheet
    18. Worksheets.Add After:=Sheets(sheetcount)
    19.  
    20. 'Count Worksheets
    21. sheetcount = Worksheets.Count
    22.  
    23. 'Name the sheet and add the number of sheets
    24. Worksheets(sheetcount).Name = "IK output"
    25.  
    26. Set xlapp = Excel.Application    'work with active excel application
    27. Set obook = xlapp.ActiveWorkbook    'work with active workbook - not specific
    28. Set wksSheet = obook.Worksheets(1)  'set wksheet to be any worksheet in the active workbook. This is because I am looping through each worksheet
    29.  
    30. ' Loop through each worksheet in active workbook - not a specific work book- looking for values that contain prefix IK  and copying it to the IK output sheet
    31.  
    32.  
    33.    j = 1
    34. For Each wksSheet In obook.Worksheets
    35. Filelength = wksSheet.usedrange.Rows.Count
    36.     For i = 1 To Filelength
    37.    
    38.     thiscell = Cells(i, 1)
    39.     If Left(thiscell, 2) = "IK" Then
    40.     Worksheets("IK output").Cells(j, 1).Value = Cells(i, 1).Value
    41.         j = j + 1
    42.     Else
    43.     End If
    44.     Next i
    45. Next wksSheet
    46.  
    47.  
    48.  
    49. End Sub

  4. #4
    New Member
    Join Date
    Dec 2006
    Posts
    5

    Re: Looping through sheets problems and setting of variables - vba

    Give this a try

    VB Code:
    1. Dim k as Integer
    2.  
    3. For k = 1 to Sheets.Count - 1
    4.  
    5. Set wksSheet = Sheets(k)
    6.  
    7. Filelength = wksSheet.usedrange.Rows.Count
    8.     For i = 1 To Filelength
    9.    
    10.     thiscell = wksSheet.Cells(i, 1)
    11.     If Left(thiscell, 2) = "IK" Then
    12.     Worksheets("IK output").Cells(j, 1).Value = thiscell.Value
    13.         j = j + 1
    14.     Else
    15.     End If
    16.     Next i
    17. Next k

    ska

  5. #5
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    ska67can's code may work, you could also try the following which has
    been modified from your code..

    Notes
    I am assumeing that you are running this in the Workbook you want to
    have the results displayed in. Hence I have added ThisWorkbook. around the place.

    VB Code:
    1. Sub IKlist()
    2. Dim wksSheet As Worksheet
    3. Dim i As Long
    4. Dim Filelength As Integer
    5. Dim j As Long
    6.  
    7. ' CREATE OUTPUT SHEET IK Output
    8.  
    9. 'Count Worksheets
    10. sheetcount = ThisWorkbook.Worksheets.Count
    11.  
    12. 'Add worksheets after the last sheet
    13. ThisWorkbook.Worksheets.Add After:=Sheets(sheetcount)
    14.  
    15. ' ReCount Worksheets, Could have used [U]sheetcount=sheetcount+1[/U] instead
    16. sheetcount = ThisWorkbook.Worksheets.Count
    17.  
    18. 'Name the sheet
    19. ThisWorkbook.Worksheets(sheetcount).Name = "IK output"
    20.  
    21. ' Loop through each worksheet in active workbook
    22. ' not a specific work book- looking for values that contain
    23. ' prefix IK and copying it to the IK output sheet
    24.  
    25.  
    26.    j = 1
    27. For Each wksSheet In ThisWorkbook.Worksheets
    28.     If wksSheet.Name <> "IK output" Then ' Only work on sheets not named IK Output
    29.         Filelength = wksSheet.usedrange.Rows.Count
    30.         For i = 1 To Filelength ' Run through all used rows
    31.             If Left(wksSheet.Cells(i, 1),2) = "IK" Then
    32.               ' If the cell in the A Column Starts with IK then add to output.
    33.                Thisworkbook.Worksheets("IK output").Cells(j, 1).Value = wksSheet.Cells(i, 1).Value
    34.                 j = j + 1
    35.            End If
    36.         Next i
    37.     End If ' wksSheet.Name <> "IK output"
    38. Next wksSheet
    39.  
    40. End Sub

    The following are not needed, ThisWorkbook. replaces the obook
    We do not need to set wksSheet as that is taken care of in the For Each loop
    VB Code:
    1. Set xlapp = Excel.Application    'work with active excel application
    2. Set obook = xlapp.ActiveWorkbook    'work with active workbook - not specific
    3. Set wksSheet = obook.Worksheets(1)  'set wksheet to be any worksheet in the active workbook.
    4. '  This is because I am looping through each worksheet
    Signature Under Construction

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    Hi,

    Thanks. A slight problem has occured.

    It produces error. Sheetcount does not seem to be counting right.

    The sheet can vary - but there are 4 sheet at the mow.

    It's increasing by 1 or 2 each time the script is run.

    The below error apprears in the line in bold below.

    Run-time error 1004.

    Cannot rename a sheet to the same name as another sheet, a referenced object library or
    a workbook referenced by viusal basic







    VB Code:
    1. Sub IKlist()
    2. Dim wksSheet As Worksheet
    3. Dim i As Long
    4. Dim Filelength As Integer
    5. Dim j As Long
    6. Dim sheetcount As Integer
    7.  
    8. ' CREATE OUTPUT SHEET IK Output
    9.  
    10.  
    11. 'Count Worksheets
    12. sheetcount = ThisWorkbook.Worksheets.Count
    13.  
    14. 'Add worksheets after the last sheet
    15. ThisWorkbook.Worksheets.Add After:=ThisWorkbook.Sheets(sheetcount)
    16.  
    17. ' ReCount Worksheets, Could have used sheetcount=sheetcount+1 instead
    18. sheetcount = ThisWorkbook.Worksheets.Count
    19.  
    20. 'Name the sheet
    21. [B]ThisWorkbook.Worksheets(sheetcount).Name = "IK output"[/B]
    22.  
    23.  
    24.  
    25. ' Loop through each worksheet in active workbook
    26. ' not a specific work book- looking for values that contain
    27. ' prefix IK and copying it to the IK output sheet
    28.  
    29.  
    30.    j = 1
    31. For Each wksSheet In ThisWorkbook.Worksheets
    32.     If wksSheet.Name <> "IK output" Then ' Only work on sheets not named IK Output
    33.         Filelength = wksSheet.usedrange.Rows.Count
    34.         For i = 1 To Filelength ' Run through all used rows
    35.             If Left(wksSheet.Cells(i, 1), 2) = "IK" Then
    36.               ' If the cell in the A Column Starts with IK then add to output.
    37.                ThisWorkbook.Worksheets("IK output").Cells(j, 1).Value = wksSheet.Cells(i, 1).Value
    38.                 j = j + 1
    39.            End If
    40.         Next i
    41.     End If ' wksSheet.Name <> "IK output"
    42. Next wksSheet
    43.  
    44. End Sub

  7. #7
    New Member
    Join Date
    Dec 2006
    Posts
    5

    Re: Looping through sheets problems and setting of variables - vba

    Are you just printing or exporting sheet IK output or do you need to keep it after you've run your code?

    ska

  8. #8

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    I need to keep it or use it after I run my code.

    I just need an output sheet - don't think the worksheet code is working as well - because I added the sheet manually and then run just the sheet element - but its not working.:

    When I hover over the this ThisWorkbook below, it says object variable or with block variable not set.

    For Each wksSheet In ThisWorkbook.Worksheets

    Cheers

  9. #9

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    Any ideas, torc code is not working at all. Appreciate if someone can help, fix it. please see the comment above.

  10. #10
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    Quote Originally Posted by gphillips
    The below error apprears in the line in bold below.

    Run-time error 1004.

    Cannot rename a sheet to the same name as another sheet, a referenced object library or
    a workbook referenced by visual basic
    I think that the problem is occurring because the code that I wrote did not check to see if the Worksheet already existed.

    The function below will check to see if the named worksheet already exists.
    Note : I convert the name of the worksheet I am testing and the name it is being
    checked against to Upper Case as the Worksheet names in Excel are not
    Case Sensistive.

    VB Code:
    1. Function WkShtExists(WName As String) As Boolean
    2. ' Returns True if a worksheet WName exists in Workbook TWbk
    3. Dim Counter As Long
    4. Dim WkSheet As Worksheet
    5.     WkShtExists = False
    6.     For Each WkSheet In ThisWorkbook.Worksheets
    7.         If UCase(WName) = UCase(WkSheet.Name) Then ' Worksheet Names are not Case Sensitive
    8.             WkShtExists = True
    9.             Exit For
    10.         End If
    11.     Next WkSheet
    12. End Function

    Using this we can then modify your IKList sub, although You will need to
    decide how you want to handle the situation.

    In the modified code below I am assuming that you want to clear the contents of the IK Output sheet if it already exists.

    VB Code:
    1. Sub IKlist()
    2. Dim wksSheet As Worksheet
    3. Dim i As Long
    4. Dim Filelength As Integer
    5. Dim j As Long
    6. Dim sheetcount As Integer
    7. Const IKListSheet = "IK Output"
    8.  
    9.     If WkShtExists(IKListSheet) Then
    10.         ThisWorkbook.Worksheets(IKListSheet).Cells.ClearContents
    11.     Else
    12.         ' Create Output Sheet  IK Output
    13.         ' Count Worksheets
    14.         sheetcount = ThisWorkbook.Worksheets.Count
    15.          'Add worksheets after the last sheet
    16.          ThisWorkbook.Worksheets.Add After:=ThisWorkbook.Sheets(sheetcount)
    17.           ' ReCount Worksheets, Could have used sheetcount=sheetcount+1 instead
    18.           sheetcount = ThisWorkbook.Worksheets.Count
    19.           'Name the sheet
    20.           ThisWorkbook.Worksheets(sheetcount).Name = IKListSheet
    21.     End If
    22.  
    23.  
    24.     ' Loop through each worksheet in active workbook
    25.     ' not a specific work book- looking for values that contain
    26.     ' prefix IK and copying it to the IK output sheet
    27.     j = 1 ' j is the Line we write to on IK Output
    28.     For Each wksSheet In ThisWorkbook.Worksheets
    29.         If wksSheet.Name <> IKListSheet Then ' Only work on sheets not named IK Output
    30.             Filelength = wksSheet.usedrange.Rows.Count
    31.             For i = 1 To Filelength ' Run through all used rows
    32.                 If Left(wksSheet.Cells(i, 1), 2) = "IK" Then
    33.                    ' If the cell in the A Column Starts with IK then add to output.
    34.                    ThisWorkbook.Worksheets(IKListSheet).Cells(j, 1).Value = wksSheet.Cells(i, 1).Value
    35.                     j = j + 1
    36.                 End If
    37.             Next i
    38.         End If ' wksSheet.Name <> IKListSheet
    39.     Next wksSheet
    40. End Sub

    Last edited by Torc; Jan 24th, 2007 at 07:48 AM. Reason: Corrected spelling of call to WkShtExists function.
    Signature Under Construction

  11. #11

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    That's strange - I'm certain the sheet did not exit in first place.

    That why I added code to add the sheet IK output in my previous post.

    I don't think the worksheet IK output code works either i.e to populate results.

    I still need to create the sheet IK output - I think the roots are deeper than this.

    Any ideas.
    Thnaks

  12. #12
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    I have just checked my code, you may need to change to get it to work.

    I called the function to check if the Worksheet Exists WkShtExists, but when
    I call it in the IKList Sub I called it WkSheetExists.

    When you make that correction you will find that the code is populating the
    Output sheet as required.

    Signature Under Construction

  13. #13

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    When I paste the code in one module including the function and sub combined its stops and says function not defined.



    How do I use this function not sure where it does go and what exactly do I do, as I obnly create sub routines in vba.

    Thanks.

  14. #14
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    I have added the Test spreadsheet that I used,
    try it out and let me know the results.
    Attached Files Attached Files
    Signature Under Construction

  15. #15

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    It does not work on the attached sheet - there can be huge blank gaps between the next IK Code - on even no IK- prefix on one sheet but some on another.

    In this case you should find IK- prefix data on the 3rd and 4th sheet from end.
    But it could any random place in column A.

    I have not put the code in the attached - but just tried you code.
    I am woking with massive spreadsheets.
    Attached Files Attached Files

  16. #16
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    I created a Module in your spreadsheet, and then pasted my code in, when I
    ran it I ended up with an output sheet with 811 entries, the first four of
    which where :-

    IK-10003-166
    IK-10016-002
    IK-10159-108
    IK-10159-124

    Is this the result you want?

    May be a bit late to ask this but what version of Excel are you using?
    Last edited by Torc; Jan 24th, 2007 at 10:02 AM. Reason: Neating up
    Signature Under Construction

  17. #17

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    I am using excel 2003. I am running this on C drive using all my macros saved in personal xls.


    It is still not working - I added a msgbox finish at the end of code.

    Its zooms to the msgbox that but with no errors.

    It does not even create the sheet.

  18. #18
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    Weird,

    It works for me.

    I removed Sheet1_1 in order to get this in as an attachment.

    Attached Files Attached Files
    Signature Under Construction

  19. #19

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    Hia,

    My personal xls Microsoft excel sheet object does not seem to mapping to the sheet I am running the code on. I thought this would be automatic.


    where as yours do as you saved yours to VBAProject test.xls.


    How do I correct. Think its not working becuase its not regognising my excel objects.

    My personal xls contain 16 Microsoft excel sheet objects .

  20. #20
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    Just to check,

    Do you mean that you have put the macro into a spreadsheet called personal.xls
    but are trying to run it for data in another spreadsheet, i.e. ResultsData.xls

    Signature Under Construction

  21. #21

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    I have just tried other macros and they seem to work on other spreadsheets - from personal.xls. This suggest that its not this.


    Personal.xls is where all the macros are stored saved. Its standard VB place for storing macros on c drive.


    Perhaps there is disavantages to using thisworkbook. None of my other macros use thisworkbook.


    It work's on the file your spreadsheet you sent on file -but when I run it exactly the same code on personal xls it does not.

    I need to run this code on any random spreadsheet that I want to run it on.


  22. #22
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    I understand your problem now, I wrote the macro to be run from the
    spreadsheet you held your data in, not from another spreadhseet.

    That is why I used ThisWorkbook, which references the workbook the macro
    is being run from.

    I suggest that you check the spreadsheet personal.xls, it should have a
    sheet called IK Output if you have run the macro from it.

    I will consider ways to modify the macro to be run from another spreadsheet.

    Will get back to you with an answer soon.
    Signature Under Construction

  23. #23

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    Hia,personal.xls is not a spreadsheet, it is the Project explorer tree structure.

    VBAProject (Personal).xls.


    This is a global macro storage place where macros are stored on C Drive . It is the defualt place for global macros to be stored.
    It is also should be your global place - its certainly the same on my home computer by default.


    I found out that this code works fine as long as you insert module in the specific VBA project workbook tree structure you want to use it on i.e.

    VBAProject (Test).xls

    Its does not appear to be for global macro use which might be a limitation of thisworkbook.


    After attempting to run it on personal xls tree structure it seems to be have changed Microsoft excel object sub tree structure sheet names to sheet2(IK output) and IK outputss(my 2nd attempt).

    I am worried about long term damage here becuase it does not seem to be removing itself - and am worried other global macros would expect i.e sheet2 to be named IK Output otherwise it will screw it up.

    Help would be appreciated here.

    I need this macro to be global - not specific
    I need any potential problems as a result of running it globally on personal.xls to be fixed.The problems are Microsoft Excel Objects sheet names in personal xls.(If long term damage has been done I don't know).


    Thanks

  24. #24
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    As far as I am aware neither long term damage, nor short term damage will
    have been done.

    I do not see VBA Project (Personal.xls) in my Project tree structure.

    I think that if you have a hunt around then you will probably find a
    spreadsheet called Personal.xls somewhere on your C drive.

    As far as turning my code into "Global" code is concerned I have come up
    with two ways.

    For the sake of clarity I will separate them into two different posts.

    In this first one the spreadsheet is opened using Workbooks.Open and the full
    path name, We then call the IKList Sub, passing just the File name, with
    extension; but without any Path.

    We then use this to reference the Workbook we are working on by using
    Workbooks(WkBkName) in place of ThisWorkbook

    VB Code:
    1. Option Explicit
    2. Sub Test()
    3.     Workbooks.Open "f:\test.xls"
    4.     IKlist "test.xls"
    5.     Workbooks("test.xls").Close SaveChanges:=True
    6. End Sub
    7. Function WkShtExists(ByVal WkBkName As String, ByVal WName As String) As Boolean
    8. ' Returns True if a worksheet WName exists in Workbook TWbk
    9. Dim Counter As Long
    10. Dim WkSheet As Worksheet
    11.     WkShtExists = False
    12.     For Each WkSheet In [B]Workbooks(WkBkName)[/B].Worksheets
    13.         If UCase(WName) = UCase(WkSheet.Name) Then ' Worksheet Names are not Case Sensitive
    14.             WkShtExists = True
    15.             Exit For
    16.         End If
    17.     Next WkSheet
    18. End Function
    19. Sub IKlist(ByVal WkBkName As String)
    20. Dim wksSheet As Worksheet
    21. Dim i As Long
    22. Dim Filelength As Integer
    23. Dim j As Long
    24. Dim sheetcount As Integer
    25. Const IKListSheet = "IK Output"
    26.  
    27.     If WkShtExists(WkBkName, IKListSheet) Then
    28.         Workbooks(WkBkName).Worksheets(IKListSheet).Cells.ClearContents
    29.     Else
    30.         ' Create Output Sheet  IK Output
    31.         ' Count Worksheets
    32.         sheetcount = Workbooks(WkBkName).Worksheets.Count
    33.          'Add worksheets after the last sheet
    34.          Workbooks(WkBkName).Worksheets.Add After:=Workbooks(WkBkName).Sheets(sheetcount)
    35.           ' ReCount Worksheets, Could have used sheetcount=sheetcount+1 instead
    36.           sheetcount = Workbooks(WkBkName).Worksheets.Count
    37.           'Name the sheet
    38.           Workbooks(WkBkName).Worksheets(sheetcount).Name = IKListSheet
    39.     End If
    40.  
    41.  
    42.     ' Loop through each worksheet in active workbook
    43.     ' not a specific work book- looking for values that contain
    44.     ' prefix IK and copying it to the IK output sheet
    45.     j = 1 ' j is the Line we write to on IK Output
    46.     For Each wksSheet In Workbooks(WkBkName).Worksheets
    47.         If wksSheet.Name <> IKListSheet Then ' Only work on sheets not named IK Output
    48.             Filelength = wksSheet.UsedRange.Rows.Count
    49.             For i = 1 To Filelength ' Run through all used rows
    50.                 If Left(wksSheet.Cells(i, 1), 2) = "IK" Then
    51.                    ' If the cell in the A Column Starts with IK then add to output.
    52.                    Workbooks(WkBkName).Worksheets(IKListSheet).Cells(j, 1).Value = wksSheet.Cells(i, 1).Value
    53.                     j = j + 1
    54.                 End If
    55.             Next i
    56.         End If ' wksSheet.Name <> IKListSheet
    57.     Next wksSheet
    58. End Sub

    Signature Under Construction

  25. #25
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    In this version of the code Instead of passing over teh name of the Workbook
    we pass over an actual Workbook variable which we use in place of
    ThisWorkbook

    VB Code:
    1. Option Explicit
    2. Sub Test()
    3.     Workbooks.Open "f:\test.xls"
    4.     IKlist Workbooks("test.xls")
    5.     Workbooks("test.xls").Close SaveChanges:=True
    6. End Sub
    7. Function WkShtExists(ByVal [B]WkBk As Workbook[/B], ByVal WName As String) As Boolean
    8. ' Returns True if a worksheet WName exists in Workbook TWbk
    9. Dim Counter As Long
    10. Dim WkSheet As Worksheet
    11.     WkShtExists = False
    12.     For Each WkSheet In [B]WkBk[/B].Worksheets
    13.         If UCase(WName) = UCase(WkSheet.Name) Then ' Worksheet Names are not Case Sensitive
    14.             WkShtExists = True
    15.             Exit For
    16.         End If
    17.     Next WkSheet
    18. End Function
    19. Sub IKlist(ByVal WkBk As Workbook)
    20. Dim wksSheet As Worksheet
    21. Dim i As Long
    22. Dim Filelength As Integer
    23. Dim j As Long
    24. Dim sheetcount As Integer
    25. Const IKListSheet = "IK Output"
    26.  
    27.     If WkShtExists(WkBk, IKListSheet) Then
    28.         WkBk.Worksheets(IKListSheet).Cells.ClearContents
    29.     Else
    30.         ' Create Output Sheet  IK Output
    31.         ' Count Worksheets
    32.         sheetcount = WkBk.Worksheets.Count
    33.          'Add worksheets after the last sheet
    34.          WkBk.Worksheets.Add After:=WkBk.Sheets(sheetcount)
    35.           ' ReCount Worksheets, Could have used sheetcount=sheetcount+1 instead
    36.           sheetcount = WkBk.Worksheets.Count
    37.           'Name the sheet
    38.           WkBk.Worksheets(sheetcount).Name = IKListSheet
    39.     End If
    40.  
    41.  
    42.     ' Loop through each worksheet in active workbook
    43.     ' not a specific work book- looking for values that contain
    44.     ' prefix IK and copying it to the IK output sheet
    45.     j = 1 ' j is the Line we write to on IK Output
    46.     For Each wksSheet In WkBk.Worksheets
    47.         If wksSheet.Name <> IKListSheet Then ' Only work on sheets not named IK Output
    48.             Filelength = wksSheet.UsedRange.Rows.Count
    49.             For i = 1 To Filelength ' Run through all used rows
    50.                 If Left(wksSheet.Cells(i, 1), 2) = "IK" Then
    51.                    ' If the cell in the A Column Starts with IK then add to output.
    52.                    WkBk.Worksheets(IKListSheet).Cells(j, 1).Value = wksSheet.Cells(i, 1).Value
    53.                     j = j + 1
    54.                 End If
    55.             Next i
    56.         End If ' wksSheet.Name <> IKListSheet
    57.     Next wksSheet
    58. End Sub

    Hope that one of these two methods will work for you.
    Signature Under Construction

  26. #26

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    HiA,

    Thanks, for this but I will be running my code on an already opened spreadhsheet of any random name.


    The spreadsheet will be openned manually - then I need to run the code.



    Thnaks very much for your time

  27. #27
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    Either method will work depends.

    The first method might be easier as it just needs to be passed the
    spreadsheet name of an open spreadsheet.

    i.e. you open data.xls, then you call the macro passing data.xls as a parameter.

    This could either be performed in a macro for a Command button, or by
    writing the following in the immediate window.

    IKList "data.xls"
    Signature Under Construction

  28. #28

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    Does this mean I have to keep on changing the spreadsheet name in the first open code each time for different spreadsheets I want to run it on.

    Is there a way around this?:

    It would be nice if could automatically change it for you. i,e changing test.xls to the workboook you want to run it on

    Sub Test()
    Workbooks.Open "f:\test.xls"
    IKlist Workbooks("test.xls")
    Workbooks("test.xls").Close SaveChanges:=True
    End Sub


    Not sure what to do here m8 for the way around.

  29. #29
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    How do you run macros in the Personal spreadsheet at present
    Signature Under Construction

  30. #30

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    Personal xls is the windows unhide place on excel. It may be a form of a spreadsheet where are macros are stored.

    If you click windows unhide - you should have personal xls or some other global place.


    This is a bit of code to delete duplicates - and can be run on any spreadsheet.

    It does not involve openning a spreadsheet 1st via code before use.
    Hope this explains

    VB Code:
    1. Sub DeleteDuplicates()
    2.  
    3. Dim i As Integer
    4. Dim j As Integer
    5. Dim xlapp As Worksheet
    6.  
    7.  
    8. Set xlapp = Sheets("Sheet 1")
    9.  
    10. For i = xlapp.usedrange.Rows.Count To 1 Step -1
    11.     For j = i + 1 To xlapp.usedrange.Rows.Count
    12.         If Cells(i, 1) = Cells(j, 1) And Cells(i, 5) = Cells(j, 5) Then
    13.             Rows(j).Delete
    14.             Debug.Print i
    15.         End If
    16.        
    17.     Next j
    18. Next i
    19.  
    20.  
    21. Set xlapp = Nothing
    22.  
    23. End Sub

  31. #31
    Hyperactive Member
    Join Date
    Jun 2006
    Location
    Best Place on Earth
    Posts
    363

    Re: Looping through sheets problems and setting of variables - vba

    I am using Excel 2002, I cannot see a Personal.xls file at all when coding macros.

    All three of the methods that I have posted work with my setup.

    Unfortunately I have never heard of Excel behaving in the way that yours
    does, using a Personal.xls spreadsheet.

    You could try re-writing my code, removing the references to the workbooks
    and sheets andreplacing them with references that you know work, like the xlapp in your example.

    Other than that I am stumped, maybe someone else can offer a suggestion.
    Signature Under Construction

  32. #32
    Frenzied Member zaza's Avatar
    Join Date
    Apr 2001
    Location
    Borneo Rainforest Habits: Scratching
    Posts
    1,486

    Re: Looping through sheets problems and setting of variables - vba

    To try to clear things up a bit here; Personal.xls is the file Excel generates if you elect to store macros in 'Personal Macro Workbook' when you record macros. Actually, I normally store them in 'This Workbook' but there you go. It is just a workbook like any other, and loads up with Excel so that you have access to your previously saved macros when you are running other projects.

    The DeleteDuplicates sub can be run from any book because it is added in. However, you will have trouble with it if you don't have a sheet named "Sheet1", because you've hardcoded it into the sub.


    If you want to run the code below, don't run the Test sub. Run IKList and pass the current workbook as a parameter (ActiveWorkbook) to run it from any sheet. Although I haven't scrutinised it, it doesn't look as though there is hardcoding in there that would prevent it from running on any workbook.


    If you want to run it on any xls file on your hard drive, you're going to have to open it first though. Excel can't figure out what's in the Workbook and hence take coded decisions without opening the file and having a look. You can run it in the background, so that you don't have to make the books visible, but you still have to give Excel the access.


    zaza
    I use VB 6, VB.Net 2003 and Office 2010



    Code:
    Excel Graphing | Excel Timer | Excel Tips and Tricks | Add controls in Office | Data tables in Excel | Gaussian random number distribution (VB6/VBA,VB.Net) | Coordinates, Vectors and 3D volumes

  33. #33

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    Torc - thanks for the code m8- I only have to change the workbook name in the code for it to work . However, I feel I have openned up a debate with the thisworkbook code.



    Ref : earlier solution coding by torc proposed using thisworkbook.

    Zaza, thanks for the insight into the difference between:


    why the delete duplicates code (personal.xls stored macro) works on any already previously opened spreadsheet and why the looping between different sheets code(personal.xls) does not work on an already opened spreadsheet. The looping between sheet worked if you stored the macro in a module within the specific workbook i.e. not personal.xls.


    Any more insight - you mention activeworkbook.

  34. #34

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    393

    Re: Looping through sheets problems and setting of variables - vba

    Thnaks everyone, sorry for the late reply its a excellent post.

Posting Permissions

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



Click Here to Expand Forum to Full Width