[英]Runtime error 9 when looping through file paths and opening excel
我的代码试图遍历一列并在该列中打开相关的文件路径。 由于第二个原因,尽管代码由于
运行时错误“ 9”:下标超出范围
文件路径是正确的,并且似乎并没有始终出错,因此我正在努力确定原因。 尝试通过循环第二次分配ExcelFilePath时,代码错误。
Function OpenExcels(sHt As String) As Object
Dim J As Integer
Dim ExcelFilePath As String
Dim PathLastRow As Integer
'Open Excels
PathLastRow = Sheets(sHt).Range("R" & Rows.Count).End(xlUp).Row
For J = 6 To PathLastRow
ExcelFilePath = Sheets(sHt).Range("R" & J).Value 'ERROR HERE
Module1.OpenExcelCheck ExcelFilePath
Next J
End Function
Function OpenExcelCheck(myPath As String) As Object
Dim myFileName As String
Dim FolderPath As String
Dim SaveExt As String
Dim xRet As Boolean
myFileName = Mid(myPath, InStrRev(myPath, "\") + 1, InStrRev(myPath, ".") - InStrRev(myPath, "\") - 1)
FolderPath = Left(myPath, InStrRev(myPath, "\"))
SaveExt = "." & Right(myPath, Len(myPath) - InStrRev(myPath, "."))
xRet = IsWorkBookOpen(myFileName & SaveExt)
If xRet Then
Else
Workbooks.Open (myPath)
Sleep 5000
End If
End Function
Function IsWorkBookOpen(Name As String) As Boolean
Dim xWb As Workbook
On Error Resume Next
Set xWb = Application.Workbooks.Item(Name)
IsWorkBookOpen = (Not xWb Is Nothing)
End Function
提前致谢
尝试像这样更改代码
Function OpenExcels(sHt As String) As Object
Dim J As Integer
Dim ExcelFilePath As String
Dim PathLastRow As Integer
Dim ws as worksheet
set ws = ActiveSheet
'Open Excels
PathLastRow = ws.Range("R" & Rows.Count).End(xlUp).Row
For J = 6 To PathLastRow
ExcelFilePath = ws.Range("R" & J).Value 'ERROR HERE
Module1.OpenExcelCheck ExcelFilePath
Next J
End Function
甚至最好在开始时通过正确的工作表
Function OpenExcels(ws as worksheet) As Object
Dim J As Integer
Dim ExcelFilePath As String
Dim PathLastRow As Integer
'Open Excels
PathLastRow = ws.Range("R" & Rows.Count).End(xlUp).Row
For J = 6 To PathLastRow
ExcelFilePath = ws.Range("R" & J).Value 'ERROR HERE
Module1.OpenExcelCheck ExcelFilePath
Next J
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.