Add some error checking at each stage of the process.
Option Explicit
Sub CellName()
' This macro in VBA TRIAL.xlsb
Dim wb As Workbook, ws As Worksheet
Dim sOPEXwbk As String, sOPEXsht As String
Dim msg As String, bOK As Boolean
With ThisWorkbook.Sheets("Sheet2")
sOPEXwbk = .Range("A37") ' book
sOPEXsht = .Range("A38") ' sheet
End With
' check not blank
If Len(sOPEXwbk) = 0 Or Len(sOPEXsht) = 0 Then
MsgBox "No workbook or worksheet configured on Sheet2 A37,A38", vbCritical
Exit Sub
End If
' check workbook open
For Each wb In Workbooks
msg = msg & vbCrLf & wb.Name
If wb.Name = sOPEXwbk Then bOK = True
Next
' workbook not open
If bOK = False Then
MsgBox "'" & sOPEXwbk & "' not in list" & msg, vbCritical, "Workbook not open"
Exit Sub
Else
' check worksheets
msg = ""
bOK = False
For Each ws In Workbooks(sOPEXwbk).Sheets
msg = msg & vbCrLf & ws.Name
If ws.Name = sOPEXsht Then bOK = True
Next
' worksheet not found
If bOK = False Then
MsgBox "'" & sOPEXsht & "' not in list" & msg, vbCritical, "Sheet Not Found"
Exit Sub
Else
' OK
ThisWorkbook.Sheets("Sheet2").Range("A42") = Workbooks(sOPEXwbk).Sheets(sOPEXsht).Range("B22").Value
MsgBox "Copied B22 from " & sOPEXwbk & " Sheet " & sOPEXsht, vbInformation
End If
End If
End Sub
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…