我正在尝试提示用户打开第二个 excel 工作簿以在第一个工作簿中执行“vlookup”。但是在这段代码之后宏卡住了:
s2FileName = Application.GetOpenFilename("Excel Files (*.xls;*.xlsx;*.xlsm;*.xla;*.xlam),*.xls;*.xlsx;*.xlsm;*.xla;*.xlam, All Files (*.*), *.*", 1, "Select second file")
If s2FileName = "False" Then Exit Sub
Application.DisplayAlerts = False
Set f2 = Workbooks.Open(s2FileName, UpdateLinks:=xlUpdateLinksNever)
没有弹出错误消息,即使我按“ctrl + Break”停止它,它也只是卡在那里。
但是,当我尝试将此代码分成两部分时(在提示打开第二个工作簿之前),它工作正常。这段代码有什么问题?
这是完整的代码:
Sub Mismatch()
Dim sht As Worksheet
Dim i As Integer
Dim j As Integer
Dim last As Integer
''OPEN FILE
sFileName = Application.GetOpenFilename("Excel Files (*.xls;*.xlsx;*.xlsm;*.xla;*.xlam),*.xls;*.xlsx;*.xlsm;*.xla;*.xlam, All Files (*.*), *.*", 1, "Select Authorization Issued Report File")
If sFileName = "False" Then Exit Sub
Application.DisplayAlerts = False
Set auth = Workbooks.Open(sFileName, UpdateLinks:=xlUpdateLinksNever)
'unfilter
ActiveSheet.Range("$A$1:$BH$19322").AutoFilter Field:=15
Columns("AZ:AZ").EntireColumn.Select
Selection.NumberFormat = "0"
'add new sheet
Set sht = Sheets.Add
sht.Name = "Mismatch"
Sheets("Mismatch").Select
With ActiveWorkbook.Sheets("Mismatch").Tab
.Color = 255
.TintAndShade = 0
End With
''find Mismatch
Sheets("Authorizations Issued").Select
Range("A1:BI1").Copy
Sheets("Mismatch").Select
Range("A1").Select
ActiveSheet.Paste
Sheets("Authorizations Issued").Select
last = ActiveSheet.UsedRange.Rows.Count
j = 2
For i = 2 To last
Sheets("Authorizations Issued").Select
If Range("$K$" & i).Value <> Range("$AZ$" & i).Value Then
Range("$A$" & i & ":$BH$" & i).Copy
Sheets("Mismatch").Select
Range("$A$" & j).Select
ActiveSheet.Paste
j = j + 1
Else: j = j
End If
Next i
Sheets("Mismatch").Select
ActiveSheet.UsedRange.Select
Selection.EntireColumn.EntireColumn.AutoFit
''vlookup SAP cust name
Columns("BA:BA").EntireColumn.Select
Selection.Insert Shift:=xlToRight
Range("BA2").Value = "SAP Cust Name"
mismatchLast = ActiveSheet.UsedRange.Rows.Count
Range("BA3").Select
s2FileName = Application.GetOpenFilename("Excel Files (*.xls;*.xlsx;*.xlsm;*.xla;*.xlam),*.xls;*.xlsx;*.xlsm;*.xla;*.xlam, All Files (*.*), *.*", 1, "Select second file")
If s2FileName = "False" Then Exit Sub
Application.DisplayAlerts = False
Set f2 = Workbooks.Open(s2FileName, UpdateLinks:=xlUpdateLinksNever)
cmfLast = ActiveSheet.UsedRange.Rows.Count
auth.Activate
For i = 3 To mismatchLast
Selection.Formula = "=VLOOKUP(AZ" & i & ",'[f2.name]Sheet1'!$A$1:$B$" & cmfLast & ",2,0)"
ActiveCell.Offset(1, 0).Select
Next
End Sub