简体   繁体   English

从字符串中提取文本-Excel VBA

[英]Extracting text from string - Excel VBA

I am trying to generate X,Y,Z strings from a text file to input into a CAD program like AutoCAD or Inventor. 我正在尝试从文本文件生成X,Y,Z字符串,以输入到AutoCAD或Inventor等CAD程序中。 I would like to do this in Excel using VBA. 我想在Excel中使用VBA做到这一点。

The text file contains strings like this: 文本文件包含如下字符串:

G0X.5384Z.05
G1X.634Z-.0327F.004
Z-.9184F.006
X.592Z-.9548F.004

and I would like to extract X, Y, and Z coordinates from that. 我想从中提取X,Y和Z坐标。 To be clear, this text has been pasted into Excel and Column A contains each line. 为清楚起见,此文本已粘贴到Excel中,并且A列包含每一行。 Line 1 would come out as "X.5384" in one column and "Z.05" in another. 第1行在一个列中显示为“ X.5384”,在另一列中显示为“ Z.05”。

I know enough VBA to remove the XYZ from the strings but I cannot figure out how to pull a specific portion out. 我知道足够的VBA可以从字符串中删除XYZ,但我不知道如何将特定部分拉出。 There is no guarantee that they will be in XYZ order or another letter will not be in the middle of them. 不能保证它们按XYZ顺序排列,否则不能在中间加上另一个字母。

I have read a bit about the Regex.Split and with enough time I could probably get it to split the entire string out but I would like to just pull X, Y, and Z coordinates out and ignore the rest if possible. 我已经阅读了一些有关Regex.Split的内容,并且有足够的时间我可能可以将它拆分为整个字符串,但是我想只提取X,Y和Z坐标,并尽可能忽略其余部分。

First put this little User Defined Function in a standard module: 首先将这个小的用户定义函数放在标准模块中:

Public Function GetData(r As Range, CH As String) As String
   Dim v As String, i As Long, j As Long, L As Long, CHm As String

   v = r.Text
   L = Len(v)
   GetData = ""
   i = InStr(1, v, CH)
   If i = 0 Then Exit Function
   GetData = CH

   For j = i + 1 To L
      CHm = Mid(v, j, 1)
      If CHm = "-" Or CHm = "." Or CHm Like "[0-9]" Then
         GetData = GetData & CHm
      Else
         Exit Function
      End If
   Next j
End Function

Then in B1 enter: =getdata(A1,"X") and copy down. 然后在B1中输入: =getdata(A1,"X")并向下复制。
In C1 enter: =getdata(A1,"Y") and copy down. C1中输入: =getdata(A1,"Y")并向下复制。
In D1 enter: =getdata(A1,"Z") and copy down. D1中输入: =getdata(A1,"Z")并向下复制。

在此处输入图片说明

For an alternate solution that does not use VBA, use row 1 as a header row and put in the letters you're looking for, as shown in this image: 对于不使用VBA的替代解决方案,请使用第1行作为标题行,然后输入要查找的字母,如下图所示:

样本布局

In cell B2 is this formula and then copy over and down: 在单元格B2中是此公式,然后上下复制:

=IF(COUNTIF($A2,"*"&B$1&"*")=0,"",MID($A2,SEARCH(B$1,$A2),MATCH(FALSE,INDEX(ISNUMBER(--(MID($A2&" ",SEARCH(B$1,$A2)+1,ROW($1:$10))&0)),),0)))

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

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