我制作了一个将数据从一本书传输到另一本书的宏。如果没有打开源书,宏打开它,复制数据然后关闭它,以便用户看不到发生了什么。现在出现问题 - 如果源书已经打开,则需要在操作后保持打开状态。所以,我做了一个使用我在这里找到的函数的If语句:
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
并且它第一次工作,但如果我在第一次之后再次启动宏,它就像文件未打开一样,并在完成操作时关闭它...
If IsWorkBookOpen(ActiveSheet.Range("AA1").Value) Then
Set Invoice = Workbooks(ActiveSheet.Range("AA4").Value)
openF = True
Else
openF = False
Set Invoice = Workbooks.Open(ActiveSheet.Range("AA1").Value, True, True)
End If
For Each sheet In Invoice.Worksheets
If sheet.Range("B2").Value = "active" Then
newD = vbNull
lRow = sheet.Cells(2000, 7).End(xlUp).Row
counter = sheet.Cells(2000, 1).End(xlUp).Row
totalR = num
For k = 7 To counter
If sheet.Cells(k, 6).Value = "n" Then
sheet.Range("A" & k, "F" & k).Copy
rep.Range("A" & num, "F" & num).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
rep.Cells(num, 7) = newD
If Year(rep.Cells(num, 7).Value) = Year(1) Then rep.Cells(num, 7).Clear
newD = DateAdd("d", sheet.Cells(3, 2).Value, newD)
num = num + 1
End If
Next k
rep.Cells(num, 4) = "Total"
rep.Cells(num, 5) = Application.Sum(rep.Range("E" & totalR, "E" & (num - 1)))
rep.Cells(num, 5).NumberFormat = "$#,###0"
num = num + 3
End If
Next sheet
If openF = False Then
Invoice.Close False
Set Invoice = Nothing
End If
Application.ScreenUpdating = True
问题是:第一轮宏代码是否以某种方式更改了源书的状态或名称,以便该功能不会将其视为“打开”?
答案 0 :(得分:1)
您可以通过循环查看工作簿来检查文件是否在Excel中打开,并检查名称。
Public Function IsWorkbookOpen(WorkbookName) As Boolean
Dim i As Long
For i = 1 To Workbooks.Count
If Workbooks(i).Name = WorkbookName Then
IsWorkbookOpen = True
Exit Function
End If
Next i
End Function
答案 1 :(得分:0)
有两种简单的方法:
循环工作簿,或将其设置为带有错误处理的变量(如果错误<> 0则不会打开)。
如果你有单独的excel应用程序实例,那么另一个问题可能就是你通过使用getobject循环excel应用程序来应用先前的选择。
我明天会从我的电脑上添加代码。