VBA"匹配"字符串返回错误2042

时间:2018-02-22 14:07:56

标签: excel vba excel-vba

我正在开始一个代码,它将打开一个csv文件,找到特定的列,然后将它们复制并粘贴到主要的Excel工作簿中。

csv文件会因为自动生成而在可能不同的订单中包含各种标头。在尝试复制任何信息之前,我想验证csv文件以确保存在所有必需的数据。

Dim WebImp As Workbook
Dim BackLog As String
Dim col As Long, res As Variant
Dim SearchValue As String

Private Sub CommandButton1_Click()

planned:
    MsgBox "Open a valid Web Backlog export.", vbExclamation, "Web Import"

    Application.FileDialog(msoFileDialogFilePicker).Show
    BackLog = Application.FileDialog(msoFileDialogFilePicker).SelectedItems(1)
    Set WebImp = Workbooks.Open(BackLog)
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    WebImp.Sheets(1).Activate
    SearchValue = "Summary"
    res = Application.Match(SearchValue, WebImp.Sheets(1).Rows(1), 0)
    If IsError(res) Then
        WebImp.Close
        MsgBox "File missing necessary data.", vbExclamation, "Missing Data"
        GoTo planned
    End If


End Sub

这是标题的示例。突出显示的是我试图寻找的专栏,但不能保证它将来会出现在A栏中。 enter image description here

目前,我的代码默认为

  

错误2042

并确定文件不正确,即使是带有"摘要"的单元格也是如此。存在。

我写的语法有什么问题? 为什么它没有正确抓取? 什么是潜在的解决方案?

1 个答案:

答案 0 :(得分:2)

除非有其他非打印字符(您可以通过测试Len(WebImp.Sheets(1).Range("A1")来识别,否则代码应该有效。

验证的另一种方法是使用Range.Find方法。

Dim r as Range
Set r = WebImp.Sheets(1).Rows(1)
If r.Find("Summary", LookAt:=xlWhole) Is Nothing Then
    If r.Find("Summary") Is Nothing Then
        MsgBox "Summary doesn't exist in this row"
    Else
        MsgBox "Summary exists, with additional non-printed characters."
    End If
End If
  

在尝试复制任何信息之前,我想验证csv文件以确保所有必要的数据都存在。

您也可以使用流阅读器来验证csv的内容。

Function FileContainsSummary(filepath$)
' returns the index position of "Summary" in row 1 of the CSV file
'filepath = "C:\debug\test.csv"
Dim contents As String
Dim headers() As String
Dim i As Long
Dim ret
Dim ff As Long

ff = FreeFile()

Open filepath For Binary As ff
contents = Space$(LOF(ff))
' reads the entire file contents:
'Get ff, , contents

'reads only the first line:
Line Input #ff, contents
Close ff

'~~ Let's see if "Summary" exists at all:
'   You can remove this block after debugging.
If InStr(contents, "Summary") Then
    MsgBox "Exists!"
End If

' ~~ find it's position
headers = Split(contents, ",")

' default value of -1, will return if Summary not found.
ret = -1

For i = LBound(headers) To UBound(headers)
    If headers(i) = "Summary" Then
        ret = i + 1
        GoTo EarlyExit
    End If
    If InStr(headers(i), "Summary") Then
        MsgBox "WARNING: Found, but with additional characters."
        ret = i + 1
        GoTo EarlyExit
    End If
Next

EarlyExit:
    FileContainsSummary = ret
End Function