vba 用字符串值内的空格替换下划线字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23847136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:14:03  来源:igfitidea点击:

Replace Underscores characters with Space inside a String value

excelvbaexcel-vbaexcel-2010

提问by ExoticBirdsMerchant

This is a rather simple question.

这是一个比较简单的问题。

I have a date variables formated like: 25_December_2010

我有一个格式如下的日期变量: 25_December_2010

I would like a statement or a bit of code in the VBA macrothat will transform that string value from: 25_December_2010to 25 December 2010.

我想要一个语句或一些代码VBA macro,将字符串值从: 转换25_December_201025 December 2010.

Somehow be able to remove the underscoresfrom inside the Stringvalue....

以某种方式能够underscoresString值中删除....

回答by Dmitry Pavliv

As I mentioned in comments, use code below:

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

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

回答by Rick Henderson

I wanted something similar in a macro I'm using for data cleaning so I took @simoco's answer and created a simple but mostly safe macro/sub.

我想要在用于数据清理的宏中使用类似的东西,所以我采用了@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