简体   繁体   中英

Loop Through each Cells in another workbook with a For Each Loop

quick question about the For Each In expression:
I use this line for all the rows in the same file, but different sheet:

For Each c In tarRng
        count = count + 1
        Debug.Print "c.Value: "; c.Value
        Debug.Print "cAdd: "; c.Address
        Debug.Print "count"; count
Next 

tarRng is defined as all rows of the B column which works perfect, it cycles through all rows and outputs the value in the row and the address of each value in the debug screen. The count is there for a later function which I just left out here.

Now the question: I would like to get the B column of a different Workbook in the same folder, but when I define it like this (here fixed range since I just wanted to test it).

For Each c In Workbooks("Nvm_Configuration_ASW.xlsm").Worksheets("Tabelle2").Range("B3:B271")   

It just shows the count once with the value 1 and doesn't even output c.Value or c.Address. I am sure the expression for the file and sheet are right since I tried it with the same file I am in as the filename and it worked.

Thanks, Mathias

If the workbook is not opened, you have to open it with Workbooks.Open() :

Public Sub TestMe()

    Dim myCell As Range
    Dim wks As Workbook

    Set wks = Workbooks.Open("C:\Users\Nvm_Configuration_ASW.xlsm")        
    For Each myCell In wks.Worksheets(1).Range("A1:A5")
        Debug.Print myCell
    Next        

End Sub

If it is opened, your code should be working, but it should be opened in the same Excel Instance.

By default it would be opened in the same instance, unless you do not make some additional tricks:

  • press Alt when openning it for Excel 2017
  • openning an Excel file and closing it from the small inner cross for Excel 2013 and earlier.

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