第一次海報,因此,如果有任何格式,或者我沒能堅持的指導方針,請讓我知道,這樣我可以修復它。VBA錯誤1004 - 範圍類的選擇方法失敗
所以我基本上要求Excel文件的文件目錄的用戶,那麼我設置了一些變量(最初定爲公衆項目變量,因爲這些正在使用的和在其他地方發生變化)。我也添加了這些行來設置這些變量爲空(以防萬一,我不認爲這應該很重要)。然後,我將這些變量設置爲我想要訪問的excel文件,工作簿和工作表。
Dim filepath as String
filePath = CStr(fileDialog) 'ask file dir, set to string
Dim sourceXL As Variant 'these three were orig project variables
Dim sourceBook As Variant
Dim sourceSheet As Variant
Dim sourceSheetSum As Variant
Set sourceXL = Nothing 'set to nothing in case...?
Set sourceBook = Nothing
Set sourceSheet = Nothing
Set sourceSheetSum = Nothing
Set sourceXL = Excel.Application 'set to the paths needed
Set sourceBook = sourceXL.Workbooks.Open(filePath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")
Dim measName As Variant 'create variable to access later
Dim partName As Variant
sourceSheetSum.Range("C3").Select 'THIS IS THE PROBLEM LINE
measName = sourceSheetSum.Range(Selection, Selection.End(xlDown)).Value
sourceSheetSum.Range("D3").Select
partName = sourceSheetSum.Range(Selection, Selection.End(xlDown)).Value
所以我創建了兩個不同的表變量「sourceSheets」和「sourceSheetsSum」,代碼工作,如果我使用「sourceSheets」,但如果我使用「sourceSheetsSum」錯誤1004發生。我也曾嘗試與變量「sourceSheet」完全刪除代碼,在被壓倒一切「sourceSheetSum」出於某種原因的情況下。
我相當確信excel工作簿和工作表存在,並且被正確調用,因爲我運行了一小段代碼來遍歷工作簿中的所有工作表並輸出名稱,如下所示。
For j = 1 To sourceBook.Sheets.Count
Debug.Print (Sheets(j).name)
Next j
隨着
測量調試輸出
分析摘要
分析設置
因此,沒有任何人有任何想法這是什麼錯誤可能意味着,或者我怎麼能可能會去尋找更多關於錯誤的信息嗎?
編輯: 所以我決定添加一些表名列表,不知道它是否會有所幫助。
For j = 1 To sourceBook.Sheets.Count
listSheet(j) = Sheets(j).name
Next j
Debug.Print (listSheet(2))
Set sourceSheetSum = sourceBook.Sheets(listSheet(2))
調試打印分析總結,所以我知道該板在工作簿中存在,而且不應該在名稱的「錯字」是任何問題。
代碼仍然在同一行同樣的錯誤,但。
deusxmach1na:我想你想我改變
Dim sourceXL As Variant
Dim sourceBook As Variant
Dim sourceSheet As Variant
Dim sourceSheetSum As Variant
Set sourceSheet = sourceBook.Sheets("Measurements")
要
Dim sourceXL As Excel.Application
Dim sourceBook As Excel.Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet
Set sourceSheet = sourceBook.Worksheets("Measurements")
但是,這並不能改變錯誤,我記得我是有相似,然後改變它,因爲我讀到這個變體就像一個所有的變種,而不是實際上變種是什麼。
我會昏暗你的工作表,特別是工作表,看看會發生什麼。 'Dim sourceSheetSum as Worksheet'實際上,您可能想要以更具體的方式將所有東西調暗。 – deusxmach1na