修剪工作簿(VBA)中的所有单元格

时间:2014-01-09 09:10:34

标签: excel excel-vba excel-addins vba

我试图为一个excel插件添加功能,这个插件已经开发,它修剪了旧单元末尾的前导空格,甚至可能解析文本,我需要这样做的原因只是让它转向进入一个我已经工作的超链接,但那部分很好。

这是我到目前为止所尝试的内容,我已经将active.worksheet am修剪得很好但我无法弄清楚如何:

  1. 修剪整个工作簿中使用的每个单元格。
  2. 并在可能的情况下解析文本
  3. 这是我尝试修剪整个工作簿,它只是简单的我知道它,我只是想弄清楚:

    Sub DoTrim(Wb As Workbook)
    Dim cell As Range
    Dim str As String
    Dim nAscii As Integer
    Dim wsh As Worksheet
    
    For Each wsh In Worksheets
        With wsh.UsedRange
            For Each cell In ActiveSheet.UsedRange
                str = Trim(cell)
                 If Len(str) > 0 Then
                            nAscii = Asc(Left(str, 1))
                            If nAscii < 33 Or nAscii = 160 Then
                                If Len(str) > 1 Then
                                  str = Right(str, Len(str) - 1)
                                Else
                                    str = ""
                                End If
                            End If
                        End If
                        cell = str
            Next cell
        End With
    Next wsh
    End Sub
    

    如果我听起来像是一个完整的Newb,那么任何建议都会受到欢迎,对于这种语言来说是相当新鲜的。

    TL; DR修剪单元格仅在工作表上运行,需要在整个工作簿中运行我无法弄清楚如何在整个工作中进行迭代。

    编辑:这也是修剪这些细胞的一种更快捷的方法,为我们设计的电子表格很大并且需要一段时间来修剪细胞

2 个答案:

答案 0 :(得分:9)

<强>未测试

这是你在尝试的吗?

Sub DoTrim(Wb As Workbook)
    Dim aCell As Range
    Dim wsh As Worksheet

    '~~> If you are using it in an Add-In, it is advisable 
    '~~> to keep the user posted :)
    Application.StatusBar = "Processing Worksheets... Please do not disturb..."
    DoEvents

    Application.ScreenUpdating = False

    For Each wsh In Wb.Worksheets
        With wsh
            Application.StatusBar = "Processing Worksheet " & _
                                    .Name & ". Please do not disturb..."
            DoEvents

            For Each aCell In .UsedRange
                If Not aCell.Value = "" And aCell.HasFormula = False Then
                    With aCell
                        .Value = Replace(.Value, Chr(160), "")
                        .Value = Application.WorksheetFunction.Clean(.Value)
                        .Value = Trim(.Value)
                    End With
                End If
            Next aCell
        End With
    Next wsh

    Application.ScreenUpdating = True
    Application.StatusBar = "Done"
End Sub

答案 1 :(得分:6)

我同意Siddarth:

For Each cell In ActiveSheet.UsedRange

应该是:

For Each cell In wsh.UsedRange

我原本以为你应该能够在循环中使用'With wsh.UsedRange'语句删除。

当您传入WorkBook引用时,也许您应该考虑从以下内容转换外部For循环:

For Each wsh In Worksheets

为:

For Each wsh In Wb.Worksheets