简体   繁体   English

使用For Each循环遍历另一个工作簿中的每个单元格

[英]Loop Through each Cells in another workbook with a For Each Loop

quick question about the For Each In expression: 有关For Each In表达式的快速问题:
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. tarRng定义为B列的所有行,它们可以完美工作,它遍历所有行并输出该行中的值以及调试屏幕中每个值的地址。 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). 现在的问题是:我想在同一文件夹中获得不同工作簿的B列,但是当我这样定义它时(这里是固定范围,因为我只想测试它)。

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. 它只显示一次值为1的计数,甚至不输出c.Value或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 谢谢,Mathias

If the workbook is not opened, you have to open it with Workbooks.Open() : 如果未打开工作簿,则必须使用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. 如果已打开,则您的代码应该可以正常工作, 应在同一Excel实例中打开它。

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 为Excel 2017打开时按Alt
  • openning an Excel file and closing it from the small inner cross for Excel 2013 and earlier. 打开Excel文件,然后从较小的内部十字形中将其关闭(对于Excel 2013及更早版本)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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