programing

특수 문자 VBA Excel 제거

linuxpc 2023. 7. 10. 22:06
반응형

특수 문자 VBA Excel 제거

VBA를 사용하여 일부 제목을 읽은 다음 해당 정보를 PowerPoint 프레젠테이션에 복사합니다.

문제는 제목에 특수 문자가 있지만, 제가 해결하고 있는 이미지 파일은 그렇지 않다는 것입니다.

제목은 예를 들어 JPEG를 그림 컨테이너에 로드하는 경로의 일부를 형성합니다.P k.jpg하지만 제목은.p.k.

제목의 특수 문자를 무시하고 대신 공간을 표시하여 올바른 JPG 파일을 선택할 수 있도록 하고 싶습니다.

어떻게 해야 하나요?

단순한 구두점, "특수" 문자는 무엇이라고 생각하십니까?사용할 수 있어야 합니다.Replace함수:Replace("p.k","."," ").

Sub Test()
Dim myString as String
Dim newString as String

myString = "p.k"

newString = replace(myString, ".", " ")

MsgBox newString

End Sub

여러 개의 문자가 있는 경우 사용자 지정 함수 또는 단순 연결된 일련의Replace기능 등

  Sub Test()
Dim myString as String
Dim newString as String

myString = "!p.k"

newString = Replace(Replace(myString, ".", " "), "!", " ")

'## OR, if it is easier for you to interpret, you can do two sequential statements:
'newString = replace(myString, ".", " ")
'newString = replace(newString, "!", " ")

MsgBox newString

End Sub

잠재적인 특수 문자가 많은 경우(예: 영어 이외의 악센트가 있는 ascii?)어레이에서 사용자 지정 함수 또는 반복을 수행할 수 있습니다.

Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?"  'modify as needed
Sub test()
Dim myString as String
Dim newString as String
Dim char as Variant
myString = "!p#*@)k{kdfhouef3829J"
newString = myString
For each char in Split(SpecialCharacters, ",")
    newString = Replace(newString, char, " ")
Next
End Sub

특수 문자 목록뿐만 아니라 문자나 숫자가 아닌 모든 문자를 제외하려는 경우에는 문자 유형 비교 방법을 사용하는 것이 좋습니다.

문자열의 각 문자에 대해 유니코드 문자가 "A"와 "Z" 사이, "a"와 "z" 사이 또는 "0"과 "9" 사이인지 확인합니다.다음은 vba 코드입니다.

Function cleanString(text As String) As String
    Dim output As String
    Dim c 'since char type does not exist in vba, we have to use variant type.
    For i = 1 To Len(text)
        c = Mid(text, i, 1) 'Select the character at the i position
        If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
            output = output & c 'add the character to your output.
        Else
            output = output & " " 'add the replacement character (space) to your output
        End If
    Next
    cleanString = output
End Function

위키백과의 유니코드 문자 목록은 이 기능을 좀 더 사용자 지정하고 싶다면 빠른 시작이 좋습니다.

이 솔루션은 사용자가 새로운 특수 문자를 도입하는 방법을 찾더라도 작동할 수 있다는 장점이 있습니다.또한 두 개의 목록을 함께 비교하는 것보다 빠릅니다.

특수 문자를 제거하는 방법은 다음과 같습니다.

나는 간단하게 정규식을 적용했습니다.

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

링크를 기준으로 제가 사용하는 것입니다.

Function StripAccentb(RA As Range)

Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
'Const AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
'Const RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
S = RA.Cells.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = Replace(S, A, B)
'Debug.Print (S)
Next


StripAccentb = S

Exit Function
End Function

용도:

=StripAccentb(B2) ' cell address

시트의 모든 셀에 대한 하위 버전:

Sub replacesub()
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
Range("A1").Resize(Cells.Find(what:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select '
For Each cell In Selection
If cell <> "" Then
S = cell.Text
    For i = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    S = replace(S, A, B)
    Next
cell.Value = S
Debug.Print "celltext "; (cell.Text)
End If
Next cell
End Sub

언급URL : https://stackoverflow.com/questions/24356993/removing-special-characters-vba-excel

반응형