【问题标题】:Create table using vba and variable ending row and columns, when region selects too much当区域选择过多时,使用 vba 和变量结束行和列创建表
【发布时间】:2020-09-01 22:03:31
【问题描述】:

我有一个宏,可以在我的工作簿中的每个工作表中旋转,并为该工作表上的数据创建一个表格,但是每个工作表上的数据以不同的行和列结束。使用 .Region 时,它将包含比应有的更多行和列。当我总是知道结束列时,我的代码工作正常,因为我可以使用 lRow = Cells(Rows.Count, 2).End(xlUp).Row 设置变量行,现在因为我不知道我不断得到的最大列对象'_Global'的'方法'范围'失败。 这是我的宏,有人有什么想法吗?


Dim TbName As String
Dim sh As Worksheet
Dim x As Integer
Dim lRow As Long
Dim lCol As Long
Dim s As String

For Each sh In ThisWorkbook.Worksheets


sh.Select

TbName = sh.Name & "_Tb"
'On Error Resume Next

            If IsEmpty(Range("B7").Value) = False Then
                    lRow = Cells(Rows.Count, 2).End(xlUp).Row 'find last row in set of data
                    lCol = Cells(7, Columns.Count).End(xlToLeft).Column
                    s = Range("B7", lRow & lCol).Address ' **this line does not work**
                     's = Range("B7", "D" &lrow).address ' **this line works**
                        sh.ListObjects.Add(xlSrcRange, Range(s), , xlYes).Name = _
                                TbName
                            Range(TbName).Select
                            sh.ListObjects(TbName).TableStyle = "TableStyleMedium3"
                Else
                        Application.DisplayAlerts = False
                        sh.Delete
            End If 


x = x + 1
    Next sh
    On Error GoTo 0
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

【问题讨论】:

  • Range("B7", Cells(lRow, lCol)) 考虑不使用Select,而是使用sh 限定您的范围/单元格调用。在代码运行时依赖处于活动状态的特定工作表可能会随着代码的发展而导致难以跟踪的问题。

标签: excel vba


【解决方案1】:

类似这样的:

Sub Tester()

    Dim TbName As String
    Dim sh As Worksheet, rngTable As Range
    Dim x As Integer
    Dim lRow As Long
    Dim lCol As Long
    Dim s As String, lo As ListObject

    For Each sh In ThisWorkbook.Worksheets
        If Len(sh.Range("B7").Value) > 0 Then
            lRow = sh.Cells(sh.Rows.Count, 2).End(xlUp).Row
            lCol = sh.Cells(7, sh.Columns.Count).End(xlToLeft).Column
            Set rngTable = sh.Range("B7", sh.Cells(lRow, lCol))  '<<<<<<<<

            Set lo = sh.ListObjects.Add(xlSrcRange, rngTable, , xlYes)
            lo.Name = sh.Name & "_Tb"
            lo.TableStyle = "TableStyleMedium3"
        Else
            Application.DisplayAlerts = False
            sh.Delete
        End If
    Next sh

End Sub

【讨论】:

  • 工作就像一个魅力。非常感谢您的建议的优雅!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-16
  • 2022-11-29
相关资源
最近更新 更多