如何删除修改字符串以删除新工作表中的字母

时间:2018-07-17 14:27:55

标签: excel vba excel-vba letters

因此,我一直在尝试创建宏以格式化打开新工作文件的格式,然后修改1列以从数字字符串中删除字母(例如,将20180717a更改为20180717)。 我已经尝试了几件事并提出了以下代码,但是它似乎确实可以正常工作:

Sub Creating_progress_reports()

    Dim wb As Workbook
    Dim myfilename As String

    myfilename = "xxxx.xlsx"
    Set wb = Workbooks.Open(myfilename)

    Dim str1 As String
    Dim str2 As String
    Dim rngTemp As Range
    Dim rngCell As Range

    str1 = "a"
    str2 = "b"
    str3 = "c"
    str4 = "d"

    With Workbooks("xxxx.xlsx").Sheets("xxxx")
    Set rngTemp = Columns(6).CurrentRegion

    For Each rngCell In rngTemp

    If InStr(1, rngCell, str1) > 0 Then
        rngCell = Replace(rngCell.Value, str1, "")
    End If

    If InStr(1, rngCell, str2) > 0 Then
        rngCell = Replace(rngCell.Value, str2, "")
    End If

    If InStr(1, rngCell, str1) > 0 Then
        rngCell = Replace(rngCell.Value, str3, "")
    End If
        If InStr(1, rngCell, str1) > 0 Then
        rngCell = Replace(rngCell.Value, str4, "")
    End If
    Next rngCell
    End With
End Sub

错误是vba代码通过,但结果不存在。字符串中的字母仍然存在。

1 个答案:

答案 0 :(得分:2)

.之前需要Columns(6).CurrentRegion才能引用Workbooks("xxxx.xlsx").Sheets("xxxx")

With Workbooks("xxxx.xlsx").Sheets("xxxx")
    Set rngTemp = .Columns(6).CurrentRegion

否则,它是指以下之一:

  • 代码所在的Sheet
  • ActiveSheet,如果代码不在Sheet内部;