如何使用VBA在excel宏中用//替换单引号

时间:2016-05-17 13:16:39

标签: excel vba excel-vba

我在表2中有一个字符串,字符串以"开头。 ' "单引号,我想用//替换单引号,我已经通过excel宏编写了以下代码,但是输出以'以及//然后是字符串

Sub Conversion()

Dim qtpval, selval
qtpval = "'"
selval = "//"
'qtpval = Sheets("Variables").Range("A2")
'qtpval = Left(qtpval, Len(qtpval) - 1)
'MsgBox qtpval
'selval = Sheets("Variables").Range("B2")
'MsgBox selval

MoveCode qtpval, selval

'readvariables

End Sub

Function MoveCode(qtpval, selval)

Dim lRowCount As Long

Application.ActiveSheet.UsedRange
lRowCount = Worksheets("QTP Code").UsedRange.Rows.Count
'MsgBox lRowCount

Dim i
Dim j
j = 1

For i = 1 To lRowCount

tempvar = Sheets("QTP Code").Range("A" & i)
chngval = Replace(tempvar, qtpval, selval)
'If InStr(tempvar, "'") Then
'MsgBox "pass"

'Sheets(3).Range("A" & j).Value = "//" & tempvar
Sheets(3).Range("A" & j).Value = chngval
j = j + 1
'End If

Next i

End Function

'Function readvariables()

'Dim varRowCount As Long

'Application.ActiveSheet.UsedRange
'varRowCount = Worksheets("Variables").UsedRange.Rows.Count
'MsgBox varRowCount

'End Function

1 个答案:

答案 0 :(得分:3)

问题是单引号是 PreFixCharacter ,它不出现在单元格中,而只是控制格式。例如,如果输入:

'A

你会得到一个单元格:

enter image description here

引号出现在公式栏中,但不在单元格中。事实上,如果你检查 A1 的长度,它只会 1

由于单引号不存在, Replace()无法将其删除。而是考虑:

Sub DontQuoteMe()
    Dim s As String, r As Range

    Set r = Range("A1")
    s = r.Value
    MsgBox Len(s) & vbCrLf & s

    If r.PrefixCharacter = "'" Then
        r.Value = "//" & r.Value
    End If

End Sub

这将

  • 使用PreFixCharacter定位单元格
  • 预先添加斜杠
  • 删除PreFixCharacter

修改#1:

此宏将遍历单元格并修复具有PreFixCharacter的那些:

Sub QuoteKleaner()
    Dim s As String, r As Range
    Dim rBig As Range

    Set rBig = ActiveSheet.UsedRange.Cells.SpecialCells(xlCellTypeConstants)
    For Each r In rBig
        If r.PrefixCharacter = "'" Then
            r.Value = "//" & r.Value
        End If
    Next r
End Sub