VBA替换()不起作用

时间:2018-02-12 16:16:54

标签: excel vba excel-vba replace

命令Replace()对我不起作用。我终于得到了它的工作,但只是跳过错误消息。为什么命令在有错误时有效,不要问,这是我的工作代码。任何人都可以解释我哪里出错了吗?

If Target.Address(0, 0) = "E3" Then
   Range("E3").Select
   On Error Resume Next
   Selection.NumberFormat = "@"
   Selection.Replace What:="-", Replacement:=""
   Selection.Replace What:=" ", Replacement:=""
   Selection = UCase(Selection.Value)
End If

另外,为什么不能做这样的工作呢?

selection.value = replace(selection.value," ", "")

为那些想要的人提供一些背景信息:我使用它去除" - "并自动从产品样式编号中抽出空格。例如05402-pt072 004需要等于05402pt072004。

感谢任何回复的人。

5 个答案:

答案 0 :(得分:4)

鉴于存在Target,我假设代码处于Worksheet_Change事件中。

那说,以下应该有效:

If Target.Address(0, 0) = "E3" Then

   Application.EnableEvents = False 'stop change event from firing again
   With Target
       .NumberFormat = "@"
       .Replace What:="-", Replacement:=""
       .Replace What:=" ", Replacement:=""
       .Value = UCase$(.Value)
   End With
   Application.EnableEvents = True

End If

答案 1 :(得分:1)

我假设您正在进入无限循环,因为每次更新targetcell时,workheet_change事件都会启动。 <怎么样

    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim s As String
    If Target.Address = "$E$3" Then
        Application.EnableEvents = False
        s = Target
        s = Replace(s, " ", "")
        s = Replace(s, "-", "")
        Target = Format(s, "@")
        Application.EnableEvents = True
    End If
End Sub

答案 2 :(得分:0)

在新的Excel工作表上写下:

outer.get('/account', function(req, res) {
  var id = req.user.uid
  var userRef = firebase.db.collection('users').doc(id)
  var profilePromise = userRef.get().then(doc => {
    if (doc.exists) {
      var profile = doc.data()
      profile.id = doc.id
      return profile // I assume you don't want to return undefined
//    ^^^^^^
    } else {
      throw new Error("Profile doesn't exist")
//    ^^^^^
    }
  })
  // More promises further on, which I wait for:
  // profilePromise.then(myProfile => { … });
})
  • 然后按 F5 Sub TestMe() Range("A1") = "05402-pt072 004" Stop Range("A1").Value = Replace(Range("A1").Value, " ", "") Stop Range("A1").Value = Replace(Range("A1").Value, "-", "") End Sub 上显示05402-pt072 004
  • F5 。现在A1上的文字是A1
  • F5 。现在05402-pt072004上的文字是A1

享受!

下一步,您可以从代码中删除05402pt072004。然后尝试编写.Value等。

答案 3 :(得分:0)

这也有效:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$E$3" Then
       Target.NumberFormat = "@"
       Value = Target.Value
       Value = Replace(Value, "-", "")
       Value = Replace(Value, " ", "")
       Target.Value = UCase(Value)
    End If
End Sub

答案 4 :(得分:0)

尝试使用以下

替换您的代码
If Not Application.Intersect(Target, Me.Range("E3")) Is Nothing Then
    With Target
        .NumberFormat = "@"
        Replace expression:=.Value2, Find:="-", Replace:=vbNullString
        Replace expression:=.Value2, Find:=" ", Replace:=vbNullString
        .Value2 = UCase(.Value2)
    End With
End If