簡體   English   中英

VBA“匹配”,字符串返回錯誤2042

[英]VBA “Match” with string returning error 2042

我正在開始一段代碼,該代碼將打開一個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列中。 在此處輸入圖片說明

目前,我的代碼默認為

錯誤2042

並確定文件不正確,即使存在帶有“摘要”的單元格也是如此。

我寫的語法有什么問題? 為什么不能正確抓住? 有哪些潛在的解決方案?

除非還有其他非打印字符(可以通過測試Len(WebImp.Sheets(1).Range("A1")來識別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

暫無
暫無

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

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