在VBA中分割文字

时间:2019-04-02 04:01:53

标签: excel vba

我正试图在显示图纸编号的图纸编号之前拆分一个字符串列表。

我尝试过使用left和trim之类的公式,然后使用Application.WorksheetFunction.Find命令在VBA中重写它们,但是我什么都没有。

Sub GetIssued()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object


Set objFSO = CreateObject("scripting.FileSystemObject")

r = 14


fle = ThisWorkbook.Sheets("Header Info").Range("D11") & "\"

Set objFolder = objFSO.GetFolder(fle)


With Sheets("TELECOM")
Range("A14", "I305").ClearContents
For Each objFile In objFolder.Files
    Cells(r, 9) = objFile.Name
    drwnName = Left(TELECOM.Cells(r, "I"), 
    Application.WorksheetFunction.Find("s", TELECOM.Cells(r, "I")) - 1)
    Cells(rw, "B") = drwnName
    Cells(rw, 9).ClearContents
    rw = rw + 1
Next
End With

End Sub

我只希望字符串在“ s”之前,然后在另一个单元格中检索“ s”之后和“ ^”之前的数据。

2 个答案:

答案 0 :(得分:1)

实现此目的的多种方法:

(1)要提取的字符串的长度始终相同

splitstr = Left(.Cells(r, "I").Value,8)

(2)使用拆分功能

This function根据定界符将字符串拆分为数组

splitarr = Split(.Cells(r, "I").Value, "s")
splitstr = splitarr(0) 'would return the first split string

(2)使用Instr函数

This function确定子字符串在字符串中的位置。这可以确定您要提取的字符串的长度

splitlength = Instr(1, .Cells(r, "I").Value, "s") - 1
splitstr = Left(.Cells(r, "I").Value, splitlength)

答案 1 :(得分:0)

使用Instr()函数来搜索字符串中的字符,而不是使用Find()方法来搜索Range中的字符串。

并在“ With someSheetReference ... End With”块内的所有范围引用之前加一个点,以使这些范围与该图纸引用相符。

With Sheets("TELECOM")
    .Range("A14", "I305").ClearContents
    For Each objFile In objFolder.Files
        .Cells(r, 9) = objFile.Name
        drwnName = Left(.Cells(r, "I").Value, 
Instr(.Cells(r, "I").Value, "s") - 1)
        .Cells(rw, "B") = drwnName
        .Cells(rw, 9).ClearContents
        rw = rw + 1
    Next
End With