使用Try and Catch函数跳过不匹配的单元格

有人帮我在Excel中使用VBA的代码。 我的代码如下:

Sub VidyaGames() Dim LastRow As Variant, j As Integer LastRow = Range("A65536").End(xlUp).Address j = 2 For i = 1 To Range("A1", LastRow).Rows.Count + 1 Step 10 Worksheets("Sheet1").Cells(j, 1) = Worksheets("PlayerInfoAll").Cells(i, 2) Worksheets("Sheet1").Cells(j, 2) = Worksheets("PlayerInfoAll").Cells(i + 1, 2) Worksheets("Sheet1").Cells(j, 3) = Application.WorksheetFunction.Sum(Worksheets("PlayerInfoAll").Range(Cells(i + 3, 1), Cells(i + 3, 1).End(xlToRight))) Worksheets("Sheet1").Cells(j, 4) = Application.WorksheetFunction.Sum(Worksheets("PlayerInfoAll").Range(Cells(i + 4, 1), Cells(i + 4, 1).End(xlToRight))) Worksheets("Sheet1").Cells(j, 5) = Worksheets("PlayerInfoAll").Cells(i + 5, 2) Worksheets("Sheet1").Cells(j, 6) = Worksheets("PlayerInfoAll").Cells(i + 6, 2) Worksheets("Sheet1").Cells(j, 7) = Worksheets("PlayerInfoAll").Cells(i + 7, 2) Worksheets("Sheet1").Cells(j, 8) = Worksheets("PlayerInfoAll").Cells(i + 8, 2) Try Worksheets("Sheet1").Cells(j, 9) = Application.WorksheetFunction.IsNA ((Application.WorksheetFunction.Match(730, Worksheets("PlayerInfoAll").Range(Cells(i + 2, 1), Cells(i + 2, 1).End(xlToRight)), 0))) Catch Worksheets("Sheet1").Cells(j, 9) = 0 j = j + 1 Next i End Sub 

该代码从一个表格中的“块”中获取数据,并将其放入另一个工作表中的可读/类SPSS格式。 我在底部添加了Try和Catch代码,但似乎没有工作。 如果我运行没有TryCatch行的行,代码将终止,当它发现一行不包含标识符(“730”)。 我抬起头试着 抓住 ,认为这是像Python的尝试除了但是当我试图运行它时,我收到消息“编译错误:子或函数没有定义”,并尝试突出显示。

Try / Catch是否像Python的Try / Except一样工作? 如果是这样,我怎么才能在这里工作?

虽然VBA没有Try / Catch块这样的东西,你可以使用标准的error handling,例如

 Sub VidyaGames() For i = 1 To Range("A1", LastRow).Rows.Count + 1 Step 10 .... Worksheets("Sheet1").Cells(j, 9) = TryCatchWorkAround(i) j = j + 1 Next i End Sub Private Function TryCatchWorkAround(i AS Integer) AS Integer On Error GoTo Handler TryCatchWorkAround = Application.WorksheetFunction.IsNA ((Application.WorksheetFunction.Match(730, Worksheets("PlayerInfoAll").Range(Cells(i + 2, 1), Cells(i + 2, 1).End(xlToRight)), 0))) Exit_TryCatchWorkAround: Exit Function Handler: TryCatchWorkAround = 0 Resume Exit_TryCatchWorkAround End Function 

这将使用VBA标准error handling执行相同的function。

VBA不提供try / catch块。 您可以尝试通过使用On Error Goto xxx来修改error handling,其中xxx是您的error handling代码所在的标签。 查看On Error Goto ...在互联网上获取更多信息。