将Excel公式转换为适用于Mid和Find函数的VBA

时间:2016-06-08 14:18:57

标签: vba excel-vba for-loop excel-formula excel

我真的很难将下面的excel公式转换为VBA。下面的函数我假设需要在for循环中,并且需要下降动态列长度。我自己一直试图编写脚本,但我似乎无法让它在没有错误的情况下运行。

= MID(A1,FIND(":",A1)+ 1,FIND("(",A1) - 查找(":&#34 ;,A1)-1)

1 个答案:

答案 0 :(得分:1)

您可以使用以下命令动态获取列长度(或最后一行):

dim ws as Worksheet
Set ws = Thisworkbook.Worksheets("mySheetNameHere")
dim lastRow, myLoop, semicolPos, bracketPos
lastRow = ws.Cells(ws.rows.count, "A").End(xlUp).Row ' this gets last row in col A

For myLoop = 1 to lastRow
    ' Find the position of the ";"  and the "(" 
    semicolPos = InStr(ws.Range("A" & myLoop).Value, ":") + 1
    bracketPos = InStr(ws.Range("A" & myLoop).Value, "(")
    newValue = Mid(ws.Range("A" & myLoop).Value, semicolPos, bracketPos - semicolPos)
    ' Put newValue into column B, one cell over from column A
    ws.Range("B" & myLoop).Value = newValue
Next