如何通过VBA移除冗余条码字符?实现文本框仅显示指定扫描数据
VBA Solution to Extract Specific Substring from Scanned Text
Got it, let's solve this! You need to pull 338-7755885 out of the scanned string P338-7755885BP0097170824 and display only that part in your text box. Here are two reliable VBA approaches tailored to different scenarios:
Approach 1: Fixed Pattern Extraction (Ideal for Consistent Format)
If your scanned text always follows the pattern [Single Letter][TargetString]BP[Rest], basic string manipulation functions will work perfectly:
Sub ExtractFixedPatternText() Dim originalScannedText As String Dim targetText As String Dim bpStartPosition As Integer ' Get the scanned text from your text box (adjust control name as needed) originalScannedText = TextBox1.Value ' Locate the start of the "BP" suffix bpStartPosition = InStr(originalScannedText, "BP") If bpStartPosition > 0 Then ' Extract from the 2nd character (skip leading "P") up to just before "BP" targetText = Mid(originalScannedText, 2, bpStartPosition - 2) Else ' Fallback if the pattern doesn't match targetText = originalScannedText MsgBox "Scanned text doesn't follow the expected format!", vbExclamation End If ' Update the text box with the extracted value TextBox1.Value = targetText End Sub
Approach 2: Regular Expression (Flexible for Variable Formats)
If your scanned text might have varying prefixes/suffixes but the target always follows the [Digits]-[Digits] pattern, regex is the more flexible choice:
Sub ExtractWithRegex() Dim originalScannedText As String Dim targetText As String Dim regexEngine As Object ' Initialize regex object Set regexEngine = CreateObject("VBScript.RegExp") originalScannedText = TextBox1.Value ' Regex pattern: match one or more digits, a hyphen, then one or more digits regexEngine.Pattern = "\d+-\d+" regexEngine.Global = False ' Only grab the first match If regexEngine.Test(originalScannedText) Then targetText = regexEngine.Execute(originalScannedText)(0).Value Else targetText = originalScannedText MsgBox "No valid target pattern found in the scanned text!", vbExclamation End If ' Update the text box TextBox1.Value = targetText End Sub
Quick Notes:
- For the first approach, double-check the control name (like
TextBox1) matches your actual form control. - The regex method works even if the leading character isn't "P" or the suffix isn't "BP"—it just hunts for the digit-hyphen-digit sequence you need.
内容的提问来源于stack exchange,提问作者Norbulus
相关产品推荐
相关产品推荐

