Excelmacros引发错误

我编写了一个似乎可以工作的macros(在一些工作表上),但对我来说似乎相当沉重。 你可以请看一下,看看是否可以做出改变,或完成不同的macros完成相同的任务。 我在许多指定的列中查找“EUR”或“USD”值。 当两个值中的任何一个被发现时,macros将对相邻的单元格执行计算,然后将原始单元格的值更改为AED。

Option Explicit Sub Change_currency() Const EUR_to_AED = 4.9 Const USD_to_AED = 3.64 Dim R As Long Dim V1 Dim V2 Dim MyValue Dim MyValue2 'Start at row 5 R = 5 While Cells(R, "K").Value <> "" If Cells(R, "K").Value = "EUR" Then Cells(R, "K").Activate MyValue = 4.9 V1 = ActiveCell.Offset(0, -2).Value V2 = ActiveCell.Offset(0, -3).Value ActiveCell.Offset(0, -2).Value = MyValue * V1 ActiveCell.Offset(0, -1).Value = V1 * EUR_to_AED * V2 ActiveCell.Value = "AED" End If While Cells(R, "K").Value <> "" If Cells(R, "K").Value = "USD" Then Cells(R, "K").Activate MyValue = 3.64 V1 = ActiveCell.Offset(0, -2).Value V2 = ActiveCell.Offset(0, -3).Value ActiveCell.Offset(0, -2).Value = MyValue2 * V1 ActiveCell.Offset(0, -1).Value = V1 * USD_to_AED * V2 ActiveCell.Value = "AED" End If 'Next row R = R + 1 Wend End Sub 

我遇到的问题与工作表上的一些数据不是数字和macros引发错误。 那么如何忽略这些错误?

任何帮助,将不胜感激…

我通常更喜欢一个For … Next循环到WhileWend,而你似乎做两次完全相同的事情,这取决于货币,所以我简化它:

 Sub Change_currency() Const EUR_to_AED As Double = 4.9 Const USD_to_AED As Double = 3.64 Dim wks As Worksheet Dim lngRow As Long Dim lngNumRows As Long Dim c As Range Dim dblConversion As Double Dim V1 As String Dim V2 As String Set wks = ActiveSheet With wks ' this gets the last row number in column 11 that has a value lngNumRows = .Cells(.Cells.Rows.Count, 11).End(xlUp).Row For lngRow = 5 To lngNumRows Set c = .Cells(lngRow, 11) Select Case c.Value Case "EUR" dblConversion = EUR_to_AED Case "USD" dblConversion = USD_to_AED End Select V1 = c.Offset(0, -2).Value V2 = c.Offset(0, -3).Value If IsNumeric(V1) And IsNumeric(V2) Then c.Offset(0, -2).Value = V1 * dblConversion c.Offset(0, -1).Value = V1 * dblConversion * V2 c.Value = "AED" End If Next lngRow End With End Sub