只在一个工作簿中运行macros

我有两个工作簿用于数据交换。 工作簿A是主要的一个,它从工作簿B提取信息。我有A运行的macros,我只想在A中执行,但是当我在B之前打开A时,macros在B中执行。如果我打开B在A之前,那么macros按预期在A中工作。

Private Sub Workbook_Open() 'If ThisWorkbook.Name = "A" Then ThisWorkbook.Sheets("Background").Select Call Background_Lists Call Find_Missing 'End If End Sub 

我试图使用表/工作簿激活以及用If语句(注释掉),没有运气。 任何指针将是伟大的!

编辑:这是Background_Lists的代码

 Sub Background_Lists() a = 0 Range("E4:E2004").Clear Range("B4:B2004").Value = Range("=Parts!B18:B2018").Value Range("D4:D2004").Value = Range("=[B.xlsx]Sheet1!A2:A2002").Value For i = 4 To 2004 If Cells(i, 4).Value >= 300000 Then Cells(4 + a, 5).Value = Cells(i, 4).Value a = a + 1 End If Next i 

结束小组

调整sub背景列表如下:

 Sub Background_Lists() a = 0 With ThisWorkbook.Sheets("Background") .Range("E4:E2004").Clear .Range("B4:B2004").Value = .Range("=Parts!B18:B2018").Value .Range("D4:D2004").Value = .Range("=[B.xlsx]Sheet1!A2:A2002").Value For i = 4 To 2004 If .Cells(i, 4).Value >= 300000 Then .Cells(4 + a, 5).Value = .Cells(i, 4).Value a = a + 1 End If Next i End With End Sub 

尝试定义每个工作簿,例如:

 Private Sub Background_Lists() Dim WorkbookA As Workbook Dim WorkbookB As Workbook Dim WorkSheetA as Worksheet Dim WorkSheetB as Worksheet Dim WorkSheetParts as Worksheet Set WorkbookA = Workbooks("PATIENT_TRACK.xlsm") Set WorkbookB = Workbooks("PATIENT_DATA.xlsx") Set WorkSheetA =WorkbookA.Worksheets("Background") Set WorkSheetB =WorkbookB.Worksheets("Sheet1") Set WorkSheetParts =WorkbookA.Worksheets("Parts") a = 0 WorkSheetA.Range("E4:E2004").Clear WorkSheetA.Range("B4:B2004").Value = WorkSheetParts .Range("B18:B2018").Value WorkbookA.Range("D4:D2004").Value = WorkSheetB.Range("A2:A2002").Value For i = 4 To 2004 If WorkSheetA.Cells(i, 4).Value >= 300000 Then WorkSheetA.Cells(4 + a, 5).Value = WorkSheetA.Cells(i, 4).Value a = a + 1 End If Next i End Sub 

现在您可以使用WorkbookA或WorkbookB代替ThisWorkbook,并将macros指向正确的工作簿。 让我知道这是否适合你。