簡體   English   中英

在此VBA模塊中找不到將數據從一個.xls文件拉到另一個文件的問題

[英]Can't find the issue in this VBA module that pulls data from one .xls file to another

這是我第一次在這里發帖。 我一直在研究VBA模塊,該模塊旨在讓用戶單擊一個按鈕即可選擇.xls文件,並從頂部(僅)表中導入所有數據,以便在其他表中進行計算。 我有該模塊的兩個完全相同的副本,可以將數據存儲到同一工作簿的兩個不同的工作表中。 其中之一工作正常。 第二個是我遇到的麻煩,只導入1-3行,我也不知道為什么(我對VBA的使用經驗幾乎為0 :)。 這是代碼-請幫助!

Private Sub btn_GetScrapReport_Click()

     '   Local Variables
    Dim wrkBook         As Workbook
    Dim fd              As FileDialog
    Dim strComPath      As String
    Dim strFilePath As String
    Dim vrtSelectedItem As Variant


    Debug.Print "Getting File Name"

     '   Using FileOpen Dialog box get target file
    strComPath = "N:\Users\OEECalc\ScrapReports"
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    With fd
        .InitialFileName = strComPath
        .AllowMultiSelect = False
        .Filters.Clear
         'Add filter to only show excel files.
        .Filters.Add "Excel files", "*.xls", 1
         ' Use the Show method to display the File Picker dialog box and return the user's action.
        If .Show = -1 Then
            strFilePath = .SelectedItems(1)
        Else
             ' The user pressed Cancel.
            MsgBox "You must select a file to import before proceeding", vbOKOnly + vbExclamation, "No file Selected, exiting"
            Set fd = Nothing
            Exit Sub
        End If
    End With

     '   Open The File and Import
    Set wrkBook = Workbooks.Open(Filename:=strFilePath, ReadOnly:=True)
    Call Import_WOData(wrkBook)
    wrkBook.Close SaveChanges:=False

    Set fd = Nothing
End Sub

Sub Import_WOData(wrkbookSource As Workbook)

     '   Local Variables


     '   Clear import data range
    ThisWorkbook.Worksheets("ScrapReport").Range("A1:A65536").EntireRow.ClearContents

     '   Assumption is that workbook only contains a single sheet and the data starts ( headers ) in A1
    With wrkbookSource.ActiveSheet
        .Range("A1", .Range("A1").End(xlDown)).EntireRow.Copy Destination:=ThisWorkbook.Worksheets("ScrapReport").Range("A1")
    End With

End Sub

另一個(工作)模塊是相同的,只是每個“ ScrapReport”實例都被“ ReleaseWO”替換了

聽起來您的問題是它沒有從工作表中導入所有數據,而是停在了第三行。 這可能是因為單元格A4為空白,並且您的代碼采用了完整且連續的數據。

此代碼塊表示從第一個單元格開始,向下繼續直到第一個空單元格,然后復制所有這些行。

With wrkbookSource.ActiveSheet
    .Range("A1", .Range("A1").End(xlDown)).EntireRow.Copy  Destination:=ThisWorkbook.Worksheets("ScrapReport").Range("A1")
End With

如果表完整且連續,則可以。 如果您的第一列可能為空,則可以將其切換為

wrkbookSource.ActiveSheet.UsedRange.Copy Destination:=ThisWorkbook.Worksheets("ScrapReport").Range("A1")

這應該選擇工作表中所有已使用的單元格,而不考慮其連續性。 它有其自身的缺點-一旦范圍被認為是“已使用”,即使它現在是空的,也幾乎總是被認為是“已使用”-但這可能對您而言並不重要,並且如果可行,也可以進行解決。

暫無
暫無

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

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