在String值中使用Space替换下划线字符

时间:2014-05-24 16:10:30

标签: excel vba excel-vba excel-2010

这是一个相当简单的问题。

我的日期变量格式如:25_December_2010

我希望VBA macro中的语句或一些代码可以将该字符串值从25_December_2010转换为25 December 2010

以某种方式可以从underscores值中删除String ....

2 个答案:

答案 0 :(得分:11)

正如我在评论中提到的,请使用以下代码:

Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate,"_"," ")

答案 1 :(得分:0)

我想在一个用于数据清理的宏中使用类似的东西,所以我采用了@ simoco的答案并创建了一个简单但最安全的宏/子。

Sub ConvertSpaceToUnderscore()
    Dim strCellValue As String

    ' Use basic error handling if more than 1 cell is selected, or
    ' possibly if something that isn't a cell is selected.
    On Error GoTo SelectionTooBig
        strCellValue = Selection.Value
        strCellValue = Replace(strCellValue, " ", "_")
        Selection.Value = strCellValue
    On Error GoTo 0

    ' Exit the sub if things went well
    Exit Sub
SelectionTooBig:
    MsgBox "Please select one cell at a time.", vbCritical, "Selection too large"
End Sub