创建 table 未选择正确的范围

Create table not selecting correct range

我找到了以下代码来获取 TrialBalance 工作表上的数据并将其转换为 vba 中的 table。它可以创建 table 并重命名它,但范围需要从 A2 开始,因为那是存储我的 table 标题的地方。

Sub ConvertTrialBalanceToTable()
Dim wb1 As Workbook

Set wb1 = ActiveWorkbook 'Trial Balance Template File

wb1.Sheets("TrialBalance").Range("A2").CurrentRegion.Select
        If ActiveSheet.ListObjects.Count < 1 Then
            ActiveSheet.ListObjects.Add.Name = ActiveSheet.Name
        End If

End Sub

将“CurrentRegion”转换为 Excel Table 当第一个单元格上方的行或左侧的列被占用时

  • 如果代码在 TrialBalance 模板文件 中,请使用 ThisWorkbook 而不是 ActiveWorkbook
Sub ConvertTrialBalanceToTable()
    
    With ActiveWorkbook.Worksheets("TrialBalance")
        If .ListObjects.Count = 0 Then
            .ListObjects.Add(xlSrcRange, _
                RefCurrentRegion(.Range("A2")), , xlYes).Name = .Name
        End If
    End With

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns a reference to the range starting with the first cell
'               of a range and ending with the last cell of the first cell's
'               Current Region.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefCurrentRegion( _
    ByVal FirstCell As Range) _
As Range
    Const ProcName As String = "RefCurrentRegion"
    On Error GoTo ClearError

    If FirstCell Is Nothing Then Exit Function
    With FirstCell.Cells(1).CurrentRegion
        Set RefCurrentRegion = FirstCell.Resize(.Row + .Rows.Count _
            - FirstCell.Row, .Column + .Columns.Count - FirstCell.Column)
    End With

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function