XLSB个人宏文件变量错误

时间:2018-06-11 01:58:50

标签: excel vba runtime-error xlsm xlsb

免责声明:这不是我的代码。我从常规的xlsm文件中获取了一个宏,并将其放在xslb文件中,以便将其用于分析。宏在xlsm中正常工作,但在xlsb文件中遇到变量问题。

ColumnToFormat标识特定列。我确认该列存在于我的“本地”窗口的工作表中。

enter image description here

Main Sub

ColumnToFormat = Application.WorksheetFunction.Match("OR_TR_OLD_BAL", ActiveSheet.Rows(1), False)

Call FormatAmounts

然而,当我开始运行FormatAmounts时,变量消失,Excel抛出运行时错误1004;应用程序定义或对象定义的错误。在测试xlsm文件时,不会发生这种情况。变量从main sub传递给helper sub。请参阅下面的FormatAmounts

enter image description here

Sub FormatAmounts()
ActiveSheet.Columns(ColumnToFormat).Select
 Selection.TextToColumns Destination:=Range(ActiveSheet.Columns(ColumnToFormat).Address), DataType:= _
        xlDelimited, TextQualifier:=xlNone, ConsecutiveDelimiter:=False, _
        Tab:=False, Semicolon:=False, Comma:=False, Space:=False, Other:= _
        False, FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
Selection.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(@_)"
End Sub

1 个答案:

答案 0 :(得分:2)

将ColumnToFormat值传递给子过程,并通过将Application.Match用于变量并测试变量的错误,在主子过程中添加错误控制。

sub main()
    dim ColumnToFormat  as variant

    ColumnToFormat = Application.Match("OR_TR_OLD_BAL", ActiveSheet.Rows(1), 0)

    if not iserror(ColumnToFormat ) then FormatAmounts clng(ColumnToFormat)
end sub

Sub FormatAmounts(c as long)
    with ActiveSheet.Columns(c)
        .TextToColumns Destination:=.cells(1), DataType:=xlDelimited, TextQualifier:=xlNone, ConsecutiveDelimiter:=False, _
                       Tab:=False, Semicolon:=False, Comma:=False, Space:=False, Other:=False, _
                       FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
        .NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(@_)"
    end with
End Sub