通过点击相同单元格中的button在两种货币之间进行转换

我想在我的Excel工作簿中创build一个函数,通过点击一个button(我们目前使用的一个货币(SLL)到另一个(DKK) SLL或DKK,取决于当前值在哪个货币)。

我的代码是:

Sub convertcurrency() Dim userrate1 As Long Dim userrate2 As Long For Each cell In ActiveWorkbook.Worksheets userrate1 = 625 If Cells.NumberFormat = "DKK" & "$ #,##0.00" _ Then cell.Value = "SLL" & userrate1 * cell.Value ElseIf Cells.NumberFormat = "SLL" & "$ #,##0.00" _ Then cell.Value = "DKK" & (1 / userrate1) * cell.Value _ End If End Sub 

但它不工作。 错误是“编译错误。否则,如果”。 但是,如果我需要包括第二个限制,我怎样才能使用else。

 Sub test() Dim userrate1 As Long Dim userrate2 As Long For Each cell In ActiveWorkbook.Worksheets userrate1 = 625 If Cells.NumberFormat = "DKK" & "$ #,##0.00" _ Then cell.Value = userrate1 * cell.Value If Cells.NumberFormat = "SLL" & "$ #,##0.00" _ Then cell.Value = (1 / userrate1) * cell.Value _ End Sub 

尝试这个

我不确定这个function,但是这个更正了语法。

 Sub convertCurrency() Dim userrate1 As Double, userrate2 As Double Dim cr As Range, currRng As Range, ws As Worksheet userrate1 = 625 userrate2 = 1 / userrate1 For Each ws In ActiveWorkbook.Worksheets With ws On Error Resume Next Set currRng = .Cells.SpecialCells(xlCellTypeConstants, xlNumbers) On Error GoTo 0 If Not currRng Is Nothing Then For Each cr In currRng If cr.NumberFormat = "DKK" & "$ #,##0.00" Then cr.Value = "SLL" & userrate1 * cr.Value '<-one of these should probably be userrate2 ElseIf cr.NumberFormat = "SLL" & "$ #,##0.00" Then cr.Value = "DKK" & (1 / userrate1) * cr.Value '<-one of these should probably be userrate2 Else 'send non-matching number format to the VBE's Immediate window (Ctrl+G) to see what was missed debug.print cr.numberformat End If Next cr End If On Error Resume Next Set currRng = .Cells.SpecialCells(xlCellTypeFormulas, xlNumbers) On Error GoTo 0 If Not currRng Is Nothing Then For Each cr In currRng If cr.NumberFormat = "DKK" & "$ #,##0.00" Then cr.Value = "SLL" & userrate1 * cr.Value '<-one of these should probably be userrate2 ElseIf cr.NumberFormat = "SLL" & "$ #,##0.00" Then cr.Value = "DKK" & (1 / userrate1) * cr.Value '<-one of these should probably be userrate2 Else 'send non-matching number format to the VBE's Immediate window (Ctrl+G) to see what was missed debug.print cr.numberformat End If Next cr End If End With Next ws End Sub 

我试图从原始问题的描述和评论中尽可能地纠正你的逻辑。 Range.SpecialCells方法只会查看不是由您的原始代码指示的公式生成的数字。