VBA like和通配符


返回 VBA 代碼示例

VBA 通配符

本教程將演示如何在 VBA 中使用通配符。

通配符用於所有編程語言和數據庫應用程序,如 SQL Server。通配符可以定義為用於替換文本字符串中的一個或多個字符的符號。例如,這個文本字符串 - “mo*” - 將找到單詞 mom、mouse、moose、mommy 等;而這個文本字符串“mo?” 只會找到單詞 mom 作為通配符?只替換一個字符。

我們將通配符與Like 運算符一起使用,它是VBA Regex的更簡單替代方案

在 VBA 中使用 Asterix (*) 通配符

Asterix 通配符替換VBA 字符串中的一個或多個字符

讓我們看一下Excel中的以下單元格區域:

VBA通配符范圍

通過在我們的 VBA 代碼中使用 Asterix 通配符,我們可以找到所有以“M”開頭的名字並將文本的顏色更改為紅色。

因此,我們遍歷該范圍並找到所有以字母 M 開頭的名字,因為我們的通配符字符串是“ M*

運行上述代碼的結果如下所示。

VBA通配符范圍紅色

 

如果我們使用通配符字符串“Ma*”——那么只有 B3 和 B4 中的名字會改變。

在 VBA 中使用問號 (?) 通配符

問號將替換 VBA 字符串中的單個字符。

考慮以下數據:

VBA通配符范圍 QMark

 

我們可以使用通配符字符串“?im”來查找任何以“im”結尾的名字

運行此代碼的結果如下所示:

VBAWildcard 范圍 QMark 結果

 
 
 
 
 
 
 
 
 
 
AutoMacro - VBA 代碼生成器

使用 [char list] 作為通配符

The example above can be modified slightly to allow us to use the question mark, in addition to a character list of allowed characters.  The wildcard string can therefore be amended to “?[e-i]m” where the first character can be anything, the second character has to be a character between e and i and the last letter has to be the character “m”.  Only 3 characters are allowed.

The result of this code would be:

VBA通配符范圍字符字符串

Using the hash (#) Wildcard in VBA

The hash (#) wildcard replaces a single digit in a VBA string.   We can match between 0 to 9.

The code above will loop through all the cells in the Range (“B3:E8”) and will change the color of the text in a cell to RED if a double-digit number is found in that cell.

VBA通配符范圍數

In the example below, the code will only change the number if the last number is a 9.

VBA通配符范圍SpecificNumber

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM