我编写了一个似乎可行的宏(在某些工作表上),但对我来说似乎相当沉重。您能否看看是否可以进行更改或完成相同任务的完全不同的宏。我在许多指定的列中寻找值“EUR”或“USD”。找到两个值中的任何一个时,宏会对相邻单元格执行计算,然后将原始单元格的值更改为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
我遇到问题,工作表上的某些数据不是数字,宏会抛出错误。那么如何忽略这些错误?
任何帮助将不胜感激......
答案 0 :(得分:2)
我通常更喜欢ForWend的For ... Next循环,你似乎做了两次完全相同的事情,这取决于货币,所以我会简化它:
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