【问题标题】:Named range giving Error 1004 'Method 'Range' Of Object 'Worksheet' Failed'命名范围给出错误 1004 '对象'工作表'的方法'范围'失败'
【发布时间】:2019-06-26 21:16:44
【问题描述】:

这段代码工作得很好,但我做了一堆其他代码来操作和读取工作表的同一区域,现在这部分不起作用。

我尝试了一堆语法,但都没有奏效。可能是我需要调整数组的大小,但由于我将它设置为等于一个范围,我认为我不必这样做。它还说问题是范围,但我不知道。我宁愿不必调整其大小,因为它从一个较大的表格中获取,该表格的行项目将是动态的,但我可以这样做并在需要时使其动态化。我确实尝试删除范围并重命名它,但它不起作用。

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

【问题讨论】:

  • 我没有包含名称代码或 cCodes 的工作表,但我确实有另一个名为代码的范围,我相信我会尝试
  • 运气不好
  • 它是动态表格的一部分,因此我需要它来引用引用表格前三列的范围
  • @FAB 有没有办法让我直接引用我要设置为数组的表的三列

标签: excel vba


【解决方案1】:

您无需为命名范围声明工作表。
命名范围存储为外部地址,包括工作表的名称。

codes = Range("cCodes")

应该足够了。

【讨论】:

  • 不合格的Range,当在工作表的代码模块之外使用时,总是解析为ActiveSheet.Range。使用它是never advised
  • @ChrisLafky 如果这为您解决了问题,那么您的命名范围在另一张纸上,而不是Sheet1,您应该使用该纸来限定.Range 调用。跨度>
  • @GSerg 那你会怎么做呢?我需要参考才能转到表格,所以我必须使用某种范围,除非我可以直接调用表格列
  • @ChrisLafky 你有Set ws = Worksheets("Sheet1")ws.Range("cCodes")。如果删除 ws. 为您修复了它,那么它一定是具有 cCodes 范围的其他工作表。所以你会有Set ws = Worksheets("Other sheet")
  • 由于某种原因它昨晚工作,但现在不能工作。我检查了它的名字来自 sheet1 我将尝试删除并重新创建范围
【解决方案2】:

据我所知,错误是因为您没有命名范围"cCodes")。

转到 Formulas -> Name Manager 并检查您的姓名。或者,直接在代码中使用范围,即:codes = ws.Range("A1:A100")

在评论中回答你的问题:

有没有办法让我直接引用我要设置为数组的表的三列

这里有一些方法可以将范围从表格操作到数组(特定行/列),然后返回到工作表(参见代码中的 cmets)。希望这会有所帮助。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 2015-11-04
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多