简体   繁体   English

Excel VBA:使用地址将单元格转换为范围

[英]Excel VBA: Convert Cells to Range using Address

I am building a module to import text into an Excel workbook. 我正在构建一个模块,以将文本导入Excel工作簿。 After it imports, I want to format the data as a table. 导入后,我想将数据格式化为表格。 The problem I have is that the import will never have the same range. 我的问题是导入将永远不会具有相同的范围。

I'm using the following code, but it throws an error, Run-time error '424': Object required. 我正在使用以下代码,但它引发错误,运行时错误'424':必需的对象。

Sub ImportRange()

  Dim ws As Worksheet
  Dim lRow As Long
  Dim lCol As Long
  Dim rng As Range

  Set ws = ThisWorkbook.Worksheets("Import")

  lRow = ws.UsedRange.Row - 1 + ws.UsedRange.Rows.Count
  lCol = ws.UsedRange.Column - 1 + ws.UsedRange.Columns.Count

  Set rng = ws.Cells(lRow, lCol).Address(True, True)

  'MsgBox Cells(lRow, lCol).Address(True, True)

End Sub

I've done quite a bit of searching, but I have been unable to find an answer or figure out how I should be doing this. 我已经做了很多搜索,但是我一直找不到答案或弄清楚应该如何做。

The end result would look something like this in the code with the start of the range always being set to $A$1: 最终结果在代码中看起来像这样,范围的开始始终设置为$ A $ 1:

ws.ListObjects.Add(xlSrcRange, Range("$A$1:$AM$90"), , xlYes).Name = _
    "Import"

If your goal is to set a range to the used range on a sheet, it can be done simpler: 如果您的目标是将范围设置为图纸上的使用范围,则可以更简单地完成它:

Set rng = ws.UsedRange

Obviously, you need to make sure that the usedrange on that sheet properly represents your imported data. 显然,您需要确保该工作表上的usedrange正确表示您导入的数据。

To convert the range to a table: 要将范围转换为表格:

Dim Import_Table As ListObject
Set Import_Table = ws.ListObjects.Add(SourceType:=xlSrcRange, Source:=rng, XlListObjectHasHeaders:=xlYes)
Import_Table.Name = "Import"

Note: the code is for Excel 2010. For later versions, replace XlListObjectHasHeaders with HasHeaders 注意:该代码适用于Excel2010。对于更高版本,请用HasHeaders替换XlListObjectHasHeaders

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM