在VBA中用字母和数字格式化多个单元格

时间:2019-02-27 15:26:00

标签: excel vba excel-2010

一段时间以来,我一直在努力解决这个问题,但无济于事。

我有一个跟踪不同类型发票的文件。发票既有数字又有字母ex。 ABC_1234_12345678。我希望excel通过在用户输入发票代码(不带下划线)之后添加下标分数来格式化发票代码。我目前有一个可以对单个单元格执行此操作的代码,但我想知道如何才能更改它的格式,使其具有选定数量的单元格。 A1-A8。我将在注释中添加代码。

谢谢您的帮助,我将非常感激。 :)

index.ts

2 个答案:

答案 0 :(得分:3)

展开您的rngWatch

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rngWatch As Range, r As Range
    Dim strOld As String
    Dim strNew As String

    'What cell is the invoice number in?
    Set rngWatch = Range("A:A")

    'Did user change it?
    If Intersect(rngWatch, Target) Is Nothing Then Exit Sub
    For Each r In Intersect(Target, rngWatch)
        strOld = r.Value

        'Are there already hypens?
        If Len(strOld) = Len(Replace(strOld, "_", "")) Then
            strNew = Left(strOld, 3) & "_" & Mid(strOld, 4, 3) & "_" & Mid(strOld, 8)

            'Turn this off for the momenet
            Application.EnableEvents = False
                r.Value = strNew
            Application.EnableEvents = True
        End If
  Next r
End Sub

注意:

如果用户通过复制/粘贴同时更改 A 列中的多个单元格,我们将使用循环。

答案 1 :(得分:0)

这取决于您希望代码如何运行。例如,您可以创建一个宏,该宏一旦运行便会处理特定范围内的所有单元格,这对我来说是一种明智的选择。您可以使宏仅处理选定的单元格,这是另一种选择。有很多方法可以做到这一点。

我已经采用了示例代码并对其进行了调整,以便处理对_MyNamedRange命名范围内的单元格所做的所有调整。万一您将相同的代码输入到1个以上的单元格中,它会使用for循环扫描相交,但您可能希望根据工作表的运行方式来消除此相交。您将需要创建一个命名范围_MyNamedRange,宏将在其中起作用。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rngWatch As Range
    Dim strOld As String
    Dim strNew As String
    Dim rngCell As Range, rngInter As Range

    'What cell is the invoice number in?
    Set rngWatch = Range("_MyNamedRange")

    'Get intersect of the change
    Set rngInter = Intersect(rngWatch, Target)

    'Exit of the change does not intersect with the named range
    If rngInter Is Nothing Then Exit Sub

    'Scan through the intersect cells and adjust the cells
    Application.EnableEvents = False
    For Each rngCell In rngInter
        strOld = rngCell.Value

        'Are there already hypens?
        strNew = ""
        If Len(strOld) = Len(Replace(strOld, "_", "")) Then strNew = Left(strOld, 3) & "_" & Mid(strOld, 4, 3) & "_" & Mid(strOld, 8)

        'Update the cell
        rngCell.Value = strNew

    Next rngCell
    Application.EnableEvents = True

End Sub