VBA:以“=”开头的单元格导致我的移动macros中出现问题

我目前有一些代码find不在第一列的单元格,并移动它们。 我正面临以“=”开头的单元格的问题。 你们可以想办法解决这个问题吗? 提前致谢。

Sub Move() Dim cel As Range, rng As Range Dim wk As Worksheet Set wk = ActiveWorkbook.ActiveSheet Set rng = wk.UsedRange For Each cel In rng If cel.Value <> "" And cel.Column <> 1 Then wk.Cells(cel.Row, 1) = cel.Value cel.Value = "" End If Next cel End Sub 

要么每次在你的每个循环

 If Cstr(cel.Value) <> "" And ... 'you need to do that for every cel.Value occurencies 

或者在开始时声明一个variables

 Dim StringInCell as String For Each cel In rng StringInCell=Cstr(cel.Value) If StringInCell... 

你也可以尝试.Text属性(虽然我还没有运气,我宁愿使用CStr)。
如果parsing的数据抛出一个错误exception或者其他东西,这也可以工作:

 ... wk.Cells(cel.Row, 1).NumberFormat = "@" wk.Cells(cel.Row, 1) = Cstr(cel.Value) 'related to the option chosen from above 

尝试这个

 Sub Move() Dim cel As Range, rng As Range Dim wk As Worksheet Set wk = ActiveWorkbook.ActiveSheet Set rng = wk.UsedRange For Each cel In rng If cel.HasFormula Then wk.Cells(cel.Row, 1).Formula = cel.Formula cel.ClearContents Else If cel.Value <> "" And cel.Column <> 1 Then With wk.Cells(cel.Row, 1) .NumberFormat = "@" '<<edit: added formatting .Value = cel.Value End with cel.Value = "" End If End If Next cel End Sub 

如果您的单元格以=开头,但不被视为公式,而是作为文本 ,则使用Sgdva的替代build议:

 Sub Move() Dim cel As Range, rng As Range Dim wk As Worksheet Set wk = ActiveWorkbook.ActiveSheet Set rng = wk.UsedRange For Each cel In rng If cel.Text <> "" And cel.Column <> 1 Then wk.Cells(cel.Row, 1) = cel.Text cel.Value = "" End If Next cel End Sub 

编辑#1:

在将版本移动到第1列之前,这个版本应该“去公式化”一个单元格:

 Sub Move2() Dim cel As Range, rng As Range Dim wk As Worksheet, s As String Set wk = ActiveWorkbook.ActiveSheet Set rng = wk.UsedRange For Each cel In rng s = cel.Text If s <> "" And cel.Column <> 1 Then wk.Cells(cel.Row, 1).Value = s cel.Value = "" End If Next cel End Sub