VBA修剪工作表问题,但一些单元格包含空间,一些单元格包含公式

时间:2018-10-23 08:15:41

标签: excel vba excel-vba excel-2010

嘿,我在excel文件中有大量数据 在开始使用数据之前,我需要将所有数据修剪一次

但是当我使用vba修剪整个工作表时,它花费了很长时间。 出现错误“类型不匹配”

整个工作表单元格,有些包含空格,有些包含公式, 一些包含与另一个excel文件的公式链接,并且将excel文件放入 在互联网服务器中

这是我的代码

Worksheets("Sheet1").Activate
For Each cell In ActiveSheet.UsedRange.SpecialCells(xlCellTypeConstants)
  If cell.HasFormula = False Then
    cell.Value = Trim(cell)
  End If
Next cell

我只想修剪没有公式的单元格。 却得到了错误。

有人可以给我一些建议吗? 我有超过3000行记录,这些记录跨越A到CZ列。

2 个答案:

答案 0 :(得分:1)

“文本到列”,固定宽度,“完成”将快速删除前导/尾随空格。

dim i as long

with Worksheets("Sheet1")
    for i=.cells(1, .columns.count).end(xltoleft).column to 1 step -1
        with .columns(i)
            .cells.TextToColumns Destination:=.cells(1), DataType:=xlFixedWidth, _
                                 FieldInfo:=Array(0, 1)
        end with
    next i
end with

顺便说一句,如果要将多个临时空格(例如,从data data减少到data data)减少到一个空格,则需要使用Application.Trim(...)而不是VBA.Trim(...)

答案 1 :(得分:0)

Worksheets("Sheet1").Activate
For Each cell In ActiveSheet.UsedRange
If Not IsError(cell) Then
cell = WorksheetFunction.Trim(cell)
End If
Next cell

最后,我使用此代码忽略该错误。我知道这不是一个好方法。