首页 > 解决方案 > VBA宏返回“#VALUE”错误的Excel公式结果而不是预期结果

问题描述

我正在尝试编写代码,将输入的前导 0 数添加到运行宏时用户当前选择的范围内的字符串中。我一直遇到错误,而不是返回预期结果,公式的评估返回#Value 错误,老实说,我不知道从哪里开始。我使用 Microsoft 提供的调试帮助文档研究了几种解决方案,但我要么不理解解决方案,要么不存在。

Sub Add_leading_00()

Dim rng As Range
Dim Area As Range
Dim leading_count As Long


leading_count = Application.InputBox(Prompt:="Enter an integer:", Type:=1)



  If Selection.Cells.Count = 1 Then
    Set rng = Selection
  Else
    Set rng = Selection.SpecialCells(xlCellTypeConstants)
  End If


  For Each Area In rng.Areas
    
Area.Value = Evaluate("Rept(0, " & leading_count & ")& & Area.Address & ")
  
  Next Area
  

End Sub

我确实有一个返回类似结果的函数,但是我尝试仅在用户在运行时选择的范围内调用该函数失败了,这对于宏的计划功能是必需的。

Function AddLeadingZeroes(ref As Range, Length As Integer)

Dim i As Integer
Dim Result As String
Dim StrLen As Integer
StrLen = Len(ref)
For i = 1 To Length
If i <= StrLen Then
Result = Result & Mid(ref, i, 1)
Else
Result = "0" & Result
End If
Next i
AddLeadingZeroes = Result
End Function

我也找到并阅读了与此主题相邻的几个讨论,但我不确定它们是否与我的错误有关。我怀疑我错过了一些非常简单的东西。

前导 0 问题

文本格式

标签: excelvbaexcel-formula

解决方案


推荐阅读