更新时间:2023-08-23 14:39:16
我会稍微分解一下代码,并使用循环,您也可以使用 System.IO
命名空间中可用的方法删除一些代码
I would break up your code a bit, and use aFor Each
loop, also you can remove some of the code by using methods available in theSystem.IO
namespace
Private Sub processFiles()
For Each file As String In lstfiles.items
processFile(file)
Next
End Sub
Private Sub processFile(FilePath As String)
'Get the filename from the fullpath
Dim filename As String = System.IO.Path.GetFileName(FilePath)
Dim linecount As Integer
Try
'Open the file
AxOfficeViewer1.Open(filename)
'Read the file
Dim doc As Word.Document
doc = AxOfficeViewer1.ActiveDocument
linecount = (doc.BuiltInDocumentProperties("NUMBER OF LINES").Value)
'Record the linecount
recordLC(filename, linecount)
Catch ex As Exception
'Record the error in the errors table
recordError(filename, ex.Message)
Finally
'Make sure the OfficeViewer is closed
If AxOfficeViewer1.IsOpened Then
AxOfficeViewer1.Close()
End If
End Try
End Sub
Private Sub recordLC(filename As String, linecount As Integer)
dgvLinecount.Rows.Add({filename, linecount})
End Sub
Private Sub recordError(filename As String, message As String)
dgvErrors.Rows.Add({filename, message})
End Sub
在循环中写入TRY..CATCH块.在CATCH中出现异常后,请提供continue or Next
.
Write TRY..CATCH block in loop. after exception in CATCH give continue or Next
.
如果您不想在发生异常时退出循环,则只需在循环中捕获该异常,对其进行处理,并继续.
例如:
If you don''t want to go out of a loop when an Exception occurs you should simply Catch the Exception in your Loop, handle it, and continue.
For example:
' A Method that takes a collection as argument.
' The IEnumerable is only for the example. In real world apps I suggest you use IEnumerable(Of T).
Private Sub DoSomething(ByVal collection As IEnumerable)
' Loop through the collection and keep a counter.
Dim counter As Integer = 0
For Each obj In collection
Try
' Do some code to handle the current Object.
' Increment the counter. Obviously this will not happen if above code raises Exception.
counter += 1
Catch ex As Exception
' Handle your Exception
' Still increment your counter.
counter += 1
End Try
Next ' simply continue with the next item in the collection, even if the previous raised an Exception.
' Do something with your counter here.
' You could optionally put this in a Finally block.
End Sub
有关正确使用Try Catch的更多信息,最后我建议您阅读我的文章.自己的文章使用Try ... Catch ...,最后! [
For more information on proper use of Try Catch Finally I can suggest you read my own article Using Try... Catch..., Finally![^].
I am not sure what you are trying to achieve, but I think this should help you.
Good luck! :)