简体   繁体   English

Excel VBA - 大写某些单词

[英]Excel VBA - Capitalise Certain Words

I am currently using this procedure which basically changes the capitalisation for all cells to Proper in a column and it works fine.我目前正在使用这个程序,它基本上将列中所有单元格的大写更改为 Proper,并且工作正常。

VBA Code: VBA 代码:

Sub sanitise_data()

x_import.Activate

 With x_import.Range("A1", Cells(Rows.Count, "A").End(xlUp))
        .value = Evaluate("INDEX(Proper(" & .Address(External:=True) & "),)")
    End With
    
End Sub

The data is all in caps:数据全部大写:

RUGBY UNION
WTA TOUR 500
WTA TOUR 1000
PGA TOUR CHAMPIONS
ATP 250
ATP 500
PGA TOUR
EIHL
EIHL
PREMIER LEAGUE
AEW
NHL
EUROPA LEAGUE
NHL
NHL
NBA
NHL
NHL
NBA
HARLEM GLOBETROTTERS 2022 SPREAD GAME TOUR

I am looking to add another loop to change back certain words to all CAPS such as EIHL, WTA,NHL,NBA etc.. which I can define in a VBA array perhaps.我希望添加另一个循环以将某些单词改回所有大写字母,例如 EIHL、WTA、NHL、NBA 等。我可以在 VBA 数组中定义它们。 The function should be smart enough to analyse each word in each cell I presume. function 应该足够聪明,可以分析我假设的每个单元格中的每个单词。

Assuming the exceptions "EIHL, WTA,NHL,NBA" as first words you might try the following using a boolean help function IsCaps() to recheck all proper conversions in a variant 2-dim datafield array data :假设异常"EIHL, WTA,NHL,NBA"作为第一个单词,您可以使用 boolean 帮助 function IsCaps()尝试以下操作,以重新检查变体 2-dim 数据字段数组data中的所有正确转换:

Sub MakeProper()
'0) First conversion to proper (by a slightly modified OP code)
    Dim rng As Range, data As Variant
    With x_import                  ' << change to any sheet Code(Name) like e.g. Sheet1,...                               
        Set rng = .Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
        data = .Evaluate("INDEX(Proper(" & rng.Address & "),)")
    End With
'1) change exceptions to UCase
    Dim i As Long
    For i = 1 To UBound(data)
        If IsCap(data(i, 1)) Then data(i, 1) = UCase(data(i, 1))
    Next i
'2) overwrite results (or use a column offset greater 0)
    rng.Offset(, 0) = data
End Sub

Note笔记

  • the point-prefix in .Cells and .Rows to reference the actually wanted sheet .Cells.Rows中的点前缀以引用实际需要的工作表
  • the point-prefix in .Evaluate to associate the evaluation content directly to the x_import sheet (so you need not pass the External:=True argument to rng.Address , though both versions are valid) . x_import .Evaluate (因此您无需将External:=True参数传递给rng.Address尽管两个版本均有效)

Help function IsCap()帮助 function IsCap()

Function IsCap(ByVal s) As Boolean
Const Delim As String = ","
Dim Caps As Variant
    Caps = Split("Eihl,Wta,Nhl,Nba", Delim) ' << use proper writing!
IsCap = UBound(Filter(Caps, Split(s & " ")(0))) > -1
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM