簡體   English   中英

VBA如何在選項顯式中使用mid函數

[英]VBA How to use mid function in option explicit

我有一個代碼,它遍歷目標文件夾和文件夾中的每個文件。

我有兩個問題

1)我如何修改此代碼並將其添加到我的主代碼中,以便它可以工作而不會因未聲明變量而出現編譯錯誤

For Each cell In Range("B1", Cells(Rows.count, "B").End(xlUp))
   With cell
       CodeExists = InStr(1, .Value, "testflow")
       'Check that "Code:" exists
       If CodeExists > 0 Then
           .Value = Mid(.Value, CodeExists + 18, 3)
       End If
   End With
Next  

2)如果問題1不能完成,

wks.Cells(BlankRow, 6).Replace What:="hometmastresh", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
wks.Cells(BlankRow, 6).Value = WorksheetFunction.Transpose(Split(wks.Cells(BlankRow, 6), "_"))

我想知道如何修改這 2 個代碼,以便我可以拆分我的原始字符串: "hometmastresh_enciivedexterXXtresh_tepootsXXXXXXXXXXXXXXtepootFile" ,它當前在 E 行,其中“X”是未知數字,並且它在每個文件中都不同。 我想將原始字符串分成“XX”到 F 行和“XXXXXXXXXXXXXX”到 G 行

使用 Left/Right 獲取字符串的末尾並用空格將它們連接起來

Dim v As String
'...
'...
If CodeExists > 0 Then
    v = Mid(.Value, CodeExists + 18, 3)
    .Value = Left(v, 8) & " " & Right(v, 6)
End If

我仍然收到“01tresh_tepoots20191204756890tepootFile”

因此,在使用.Find獲得文本后,您可以使用Split 例如

Dim s As String

s = Split("01tresh_tepoots20191204756890tepootFile", "tepoot")(1)
s = Mid(s, 2, 8) & " " & Right(s, 6)
Debug.Print s

編輯

你的代碼

If Not aCell Is Nothing Then
    aCell.Formula = Replace(aCell.Formula, , "")
    s = Split(aCell.Value, "tepoots")(1)
End If

應該如下圖所示。 這將放置“20191204 756890”或單元格中的任何數字。

If Not aCell Is Nothing Then
    s = Split(aCell.Value, "tepoots")(1)
    s = Mid(s, 2, 8) & " " & Right(s, 6)
    aCell.Value = s
End If

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM