簡體   English   中英

給出錯誤1004'對象'工作表'的方法'范圍'失敗的命名范圍”

[英]Named range giving Error 1004 'Method 'Range' Of Object 'Worksheet' Failed'

這段代碼工作得很好,但是我做了很多其他代碼來操縱和讀取工作表的相同區域,現在此部分不起作用。

我已經嘗試了很多語法語法,但是都沒有用。 可能是我需要調整數組的大小,但是由於我將其設置為一個范圍,所以我認為我不必這樣做。 還說問題是范圍,但我不知道。 我寧願不必從較大的表中調整其大小,因為該表的行項目將是動態的,但是我可以這樣做,並在需要時使其動態。 我確實嘗試刪除范圍並重命名它,但是它沒有用。

Private Sub UserForm_Initialize()

      Dim codes()
      Dim ws As Worksheet
        Set ws = Worksheets("Sheet1")
        codes = ws.Range("cCodes")         

         CostCode1.List = codes     ''these are combo boxes                        
         CostCode2.List = codes
         CostCode3.List = codes
         CostCode4.List = codes
         CostCode5.List = codes
         CostCode6.List = codes

'' ADD UNITS

End Sub

您無需為命名范圍聲明工作表。
命名范圍存儲為包含工作表名稱的外部地址。

codes = Range("cCodes")

應該足夠了。

據我所知,錯誤是因為您沒有命名范圍"cCodes" )。

轉到公式 -> 名稱管理器,然后檢查您的名稱。 或者,直接在代碼中使用范圍,即: codes = ws.Range("A1:A100")

要在評論中回答您的問題:

有沒有一種方法可以直接引用我要設置為數組的表的三列

這里有幾種方法可以處理從表到數組(特定的行/列),再到工作表的范圍(請參見代碼中的注釋)。 希望這可以幫助。

Option Explicit

Sub test()
    Dim rngData As Range
    Dim arrData As Variant

    With Range("Table1") 'this is only the content of the table, does not include the headers
        Set rngData = Range(.Cells(1, 1), .Cells(.Rows.Count, 3)) 'Set the range starting at cell row 1, col 1 - until total number of rows in table, col 3
        'Set rngData = rngData.Offset(-1).Resize(.Rows.Count + 1) 'if you want to include headers as well
        Debug.Print rngData.Address
    End With

    arrData = rngData 'allocate the data from the range to the array

    rngData.Offset(0, Range("Table1").Columns.Count + 1) = arrData 'put the array back on the sheet, 1 column to the right of the table

    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
    ws.Range("N1").Resize(UBound(arrData), UBound(arrData, 2)) = arrData 'put the array back on the sheet in a specific range

End Sub

暫無
暫無

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

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