用于添加逗号的脚本,Application.Selection无法正常工作

时间:2015-04-30 12:13:18

标签: excel vba excel-vba

我最初在网上发现了一个脚本,它允许我在每个X字符上添加一个逗号,问题是它一次只能进行一次选择,我需要这样做9000次。

我开始玩它,我非常接近让它正常工作,但我需要一些帮助。

现在当我切换“下一个s”& “循环”它的工作原理 - 但它以这种方式格式化它。

XXXXX ,, XXXX,X,

我希望它看起来像这样:

XXXXX,XXXXX,XXXXX

有一件事我最有可能用一个函数修复,但它最后添加了一个逗号,并希望它不会在结尾处添加一个字。

这是我的剧本:

Sub CommaAdd()
    Dim WorkRng As Range
    Dim s As Range
    Dim x As Long

    xTitleId = "SelectionRange"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
    Application.ScreenUpdating = False

    For Each s In WorkRng

    s = Selection.Value

    x = Len(s) \ 5
    If Len(s) Mod 5 = 0 Then
        x = x - 1
    End If
    Do Until x <= 0
        s = Left(s, x * 5) & "," & Mid(s, x * 5 + 1)
        x = x - 1
    Selection.Value = s
    Next s
    Loop
End Sub

它现在的方式我得到了这个错误:

  

接下来没有For

任何理想?

编辑:

我已经尝试了这一点,现在意识到所有它都会复制整个列中第一个选择的数据 - 每个单独的单元格都有不同的数据。

Sub CommaAdd()
    Dim WorkRng As Range
    Dim s As Range
    Dim x As Long

    xTitleId = "SelectionRange"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
    Application.ScreenUpdating = False



    For Each s In WorkRng


    x = Len(s) \ 5
    If Len(s) Mod 5 = 0 Then
        x = x - 1
    End If



    Do Until x = 0
        s = Left(s, x * 5) & "," & Mid(s, x * 5 + 1)
        x = x - 1
    Loop
    Selection.Value = s.Value
    Next s
    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

经过反复试验,让它以我想要的方式运作。以为我会分享

Sub CommaAdd()
    Dim WorkRng As Range
    Dim s As String
    Dim a As Object
    Dim x As Long

    xTitleId = "SelectionRange"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
    Application.ScreenUpdating = False

    For Each a In WorkRng
    s = a.Value
    x = Len(s) \ 5
    If Len(s) Mod 5 = 0 Then
        x = x - 1
    End If
    Do Until x = 0
        s = Left(s, x * 5) & "," & Mid(s, x * 5 + 1)
        x = x - 1
    Loop
    a.Value = s
    Next a
    Application.ScreenUpdating = True
End Sub