0

我编写了一个似乎可以工作的宏(在某些工作表上),但对我来说似乎相当繁重。您能否看一下是否可以进行更改或完成相同任务的完全不同的宏。我正在许多指定列中寻找值“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

我遇到了工作表上的某些数据不是数字的问题,并且宏会引发错误。那么如何忽略这些错误呢?

任何帮助,将不胜感激...

4

1 回答 1

2

我通常更喜欢 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
于 2013-09-16T15:35:24.587 回答