是的,如果您没有完全限定您的对象,这是一个非常常见的问题。让我们举个例子。如果我们有 4 个工作簿并且所有四个工作簿都有名为“Sheet1”的工作表,那么我们应该如何确保从正确的单元格中获取数据?
Cells(1, 1).Value
将始终从当前活动工作表中获取数据,这可能不是您真正想要的工作表。
如果您通过宏打开 4 个文件,那么这是正确的做法。
Sub Sample()
Dim wb1 As Workbook, wb2 As Workbook, wb3 As Workbook, wb4 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet, ws4 As Worksheet
Set wb1 = Workbooks.Open("C:\File1.xlsx")
Set ws1 = wb1.Sheets("Sheet1")
Set wb2 = Workbooks.Open("C:\File2.xlsx")
Set ws2 = wb2.Sheets("Sheet1")
Set wb3 = Workbooks.Open("C:\File3.xlsx")
Set ws3 = wb3.Sheets("Sheet1")
Set wb4 = Workbooks.Open("C:\File4.xlsx")
Set ws4 = wb4.Sheets("Sheet1")
'~~> Now you can work with the relevant cells
Debug.Print ws1.Cells(1, 1).Value
Debug.Print ws2.Cells(1, 1).Value
Debug.Print ws3.Cells(1, 1).Value
Debug.Print ws4.Cells(1, 1).Value
End Sub
如果您没有通过宏打开这四个文件,您仍然可以将它们设置为 wb1、wb2 等,然后按上述方式工作。