【问题标题】:Data Manipulation / Dissecting数据操作/剖析
【发布时间】:2018-12-13 14:54:28
【问题描述】:

我正在尝试剖析 VBA 中的一些文本,我尝试更改的两个文本示例如下:

原始数据

FAST CASH W5600Z *Scenario 1*
FAST CASH 5786Z *Scenario 2*

需要输出

D5600Z (Replacing the "W" with a "D") *Scenario 1*
D5786Z (Adding a "D" before the first numeric character) *Scenario 2*

这是我的数据操作的最后一部分,之前用于操作数据的代码可以在下面的代码中看到:

For Each b In wbRecFile.Sheets("Corrected Data1").Range("B1:B" & Lastrow)
    If b.Value <> "" Then     
        If UCase(Left(b.Value, 1)) = "W" Then b.Value = "D" & Right(b.Value, Len(b.Value) - 1)
        GoTo nextline
    End If

    If IsNumeric(Left(b.Value, 1)) Then b.Value = "D" & b.Value
    GoTo nextline
    End If

    End If 
nextline:     
Next b

任何关于我如何在 VBA 中实现这一点的建议将不胜感激。我能够在下面的 excel 公式中完成此任务,但我正在尽我所能避免将其作为解决方案。

="D"&RIGHT(MID(Cell reference,FIND("W",cell reference),6),5)

【问题讨论】:

  • 您在 VBA 中是否特别需要它,或者 VBA 调用 Excel 函数是否有效?只需使用 VBA 调用 Excel 函数就更容易并节省更多时间。例如Range("B10").Formula = "=SUM(B4:B9)"
  • 请注意,Then 后面都需要换行,否则语法无效。如果是错字,请edit您的问题。
  • @ycx 我可以调用 excel 函数,只是不确定如何处理数字元素(场景二),或者第一个场景是否由于“W”不存在而导致错误。跨度>
  • @peh 感谢您编辑问题 :)
  • @SB999 你可以使用 Excel 函数IFERROR

标签: excel vba


【解决方案1】:

我已经使用下面的代码来解决我的问题。

Dim bText As String

Public Sub DisectText()
    Dim myString As String
    myString = bText
    Dim position As Long
    position = GetFirstNumeric(myString)
    If position > 0 Then
    bText = "D" & Mid(myString, position, 5)
    Else
    bText = ""
    End If
End Sub

Public Function GetFirstNumeric(ByVal value As String) As Long
    Dim i As Long
    Dim bytValue() As Byte
    Dim lngRtnVal As Long
    bytValue = value
    For i = 0 To UBound(bytValue) Step 2
        Select Case bytValue(i)
            Case vbKey0 To vbKey9
                If bytValue(i + 1) = 0 Then
                    lngRtnVal = (i \ 2) + 1
                    Exit For
                End If
        End Select
    Next
    GetFirstNumeric = lngRtnVal
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2012-12-19
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多