代码
使用功能的目的是检查我桌面上的数字 xls 文件,如果找不到,则将Thisworkbook
其放在前面。
问题
如果已经打开了工作簿,那么将 Thisworkbook 放在前面不起作用(仍在后台)并且不会引发代码错误。
问题
功能Get_Highest_Numeric_Name
的原因虽然功能本身工作正常。
我尝试
过的尝试将 ThisWorkbook.Activate 替换为
AppActivate ((ThisWorkbook.Name) & " - Excel")
但是,我在 AppActivate 行收到了这个错误
无效的过程调用或参数
奇怪的是,如果我从代码窗口运行该代码,则不会引发先前的错误。
使用 AppActivate (ThisWorkbook.Name...) 的任何方式都不可靠,因为它需要在 Windows 系统上启用此选项(文件扩展名)。
感谢任何有用的评论和答案。
Private Sub Workbook_Open()
If Len(Get_Highest_Numeric_Name("D:\Users\Waleed\Desktop\", "*.xls")) = 24 Then 'for Question on Stackoverflow
MsgBox "File not found", vbCritical + vbMsgBoxSetForeground, "File not found"
ThisWorkbook.Activate
Exit Sub
End If
End Sub
Function Get_Highest_Numeric_Name(strFold As String, Optional strext As String = "*.*") As String
Dim arrD, lastName As String, lngNb As Double, El
'Return all files name in an array
arrD = Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b").StdOut.ReadAll, vbCrLf)
If UBound(arrD) = -1 Then MsgBox "Nothing could be found in the path you supplied...": Exit Function
arrD(UBound(arrD)) = "@@##": arrD = Filter(arrD, "@@##", False) 'Remove the last (empty) element
For Each El In arrD 'iterate between the array elements
If IsNumeric(Split(El, ".")(0)) Then
'Compare the lngNb variable (initially 0) with the numeric value:
If lngNb < CDbl(Split(El, ".")(0)) Then
'addapt lngNb like the bigger number
lngNb = CDbl(Split(El, ".")(0)): lastName = El
End If
End If
Next
Get_Highest_Numeric_Name = strFold & lastName 'Build the necessary path
End Function
我绝望地尝试在代码中添加一个额外的函数API到一个单独的模块中,以生成带有超时的新消息框。
无论如何,使用这个 API 解决了这个问题(我不知道为什么会这样)。
注意:如果我评论 的行MsgBoxTimeout
,问题错误再次出现。
Private Sub Workbook_Open()
If Len(Get_Highest_Numeric_Name("D:\Users\Waleed\Desktop\", "*.xls")) = 24 Then
Call MsgBoxTimeout(0, "File not found", "File not found", vbInformation + vbMsgBoxSetForeground, 0, 2000)
Exit Sub
End If
End Sub
'这个函数存在于一个单独的模块上
Public Declare Function MsgBoxTimeout Lib "user32" Alias "MessageBoxTimeoutA" ( _
ByVal hwnd As Long, ByVal lpText As String, ByVal lpCaption As String, _
ByVal wType As VbMsgBoxStyle, ByVal wlange As Long, ByVal dwTimeout As Long) As Long
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句