【问题标题】:Excel VBA formatting and variable output not always workingExcel VBA 格式和变量输出并不总是有效
【发布时间】:2018-11-07 12:53:18
【问题描述】:

如果将在“A”行输入特定值,则应将特定价格插入“D”行,然后将输入的价格显示在消息框中。

第一部分只是一个简单的设置,但对于 msgbox,我实际上遇到了一些问题。 也许是因为代码的程序?!价格就在单元格内的这一刻,而我的代码已经在尝试在空单元格中获取这个价格?! - 不确定。

Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Handler

Dim price As String

If Target.Column = 1 And Target.Value = "XY01" Then
    Application.EnableEvents = False
    Target.Offset(0, 3) = Format(0.7, "currency")
    Application.EnableEvents = True
    price = ActiveCell.Offset(0, 3).Value
    MsgBox "The price is now " & price
End If
Handler:
End Sub

真正奇怪的是在第一行里面会显示为异常:

每隔一行它就会像这样显示(它只是空的):

我的第二个问题是我已将值格式化为“货币”,但无论如何我都会收到此错误消息(在英语中,单元格被格式化为文本)。此外,通过excel工具格式化单元格,错误消息不会消失。

有什么办法可以解决这个问题吗?

谢谢你们。

==============

编辑

我已将我的代码更新为以下代码,因此我能够解决我的第二个问题,即我的值只是一个文本。

Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Handler

Dim price As String

If Target.Column = 1 And Target.Value = "XY01" Then
    Application.EnableEvents = False
    Target.Offset(0, 3).Value = 0.7
    Target.Offset(0, 3).NumberFormat = "currency"
    Application.EnableEvents = True
    price = Target.Offset(0, 3).Text
    MsgBox "The price is now " & price
End If
Handler:
End Sub

我不知道为什么,但是现在不会任何 msgbox 显示?! 此外,价格现在只会插入一次,如果我在另一个单元格中再次输入代码(一个单元格向下),代码似乎不再运行了?!

我需要重新打开 excel 才能让它再次工作。

【问题讨论】:

  • 致您的编辑:问题是您的错误处理程序是静默的。如果发生错误,它会跳转到Handler:,但什么也没有发生(根本没有消息)。因此,您不会注意到任何错误。注释掉On Error GoTo Handler 以对其进行调试并稍后实施适当的错误处理:请参阅VBA Error Handling – A Complete Guide

标签: excel vba formatting msgbox


【解决方案1】:

Format function 总是返回一个字符串/文本。

所以这里:Target.Offset(0, 3) = Format(0.7, "currency") 你写的不是数值而是文本。

改为写入值并设置单元格的数字格式:

Target.Offset(0, 3).Value = 0.7
Target.Offset(0, 3).NumberFormat = "#,##0.00 $"

然后您可以读取单元格的.Text(而不是.Value)以将其格式化为单元格所示:

Dim price As Sting
price = Target.Offset(0, 3).Text
MsgBox "The price is now " & price

或读取单元格的值并将其格式化为您喜欢的格式:

Dim price As Double
price = Target.Offset(0, 3).Value
MsgBox "The price is now " & Format(price, "#,##0.00 $")

【讨论】:

  • 谢谢,您的回答对我来说绝对有意义。但它现在似乎不起作用。我将更新我的原始帖子并提供更多详细信息。
  • @L.Writer 啊没看到。您使用了ActiveCell 而不是Target,因此它可能从您写入的另一个单元格中读取。修正了我的答案。
  • 我已经使用了你的更新,但它似乎仍然不适合我?!我已经用一些额外的细节更新了我的原始帖子,希望这会有所帮助。
  • 注释掉 On Error GoTo Handler 并告诉您您遇到了哪个错误以及在哪里。
  • 啊,我也错过了。显然"currency" 不是有效的数字格式。所以你必须使用"#,##0.00 $"之类的东西。见Range.NumberFormat PropertyRange.NumberFormatLocal Property
【解决方案2】:

您可以尝试更改此行吗:

Dim price As Double

祝你好运

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2012-11-02
    • 1970-01-01
    • 2013-08-07
    • 2012-02-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多