调整命名范围VBA的大小

时间:2017-03-31 05:17:55

标签: vba range named

VBA Excel 2016

如果在执行某些代码后该列的列数较少,我试图动态调整范围。参考MS文件和各种在线示例没有运气。 https://msdn.microsoft.com/en-us/library/office/ff193274.aspx

只有当我执行" testRange.Resize Range(" A1:G1")之类的操作时,我才能实现正确的调整大小。但是,我正在寻找以下内容:

#added duplicates
df_b = pd.DataFrame({'UID': [221, 12, 456, 456], 
                     'PID': [17, 89, 55, 55], 
                     'FOO': [2347, 32447, 3234, 7999]})
print (df_b)
     FOO  PID  UID
0   2347   17  221
1  32447   89   12
2   3234   55  456 <-duplicates by both columns
3   7999   55  456 <-duplicates by both columns

df_b = df_b.drop_duplicates(['PID','UID'])
df_a['PUR'] = df_a.join(df_b.set_index(['PID','UID']), on=['PID','UID'])['FOO']
                  .notnull().astype(int)
print (df_a)
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25   12    1

2 个答案:

答案 0 :(得分:1)

如果“命名范围”是“正常”命名范围或“表”(ListObject)范围,则调整“命名范围”大小的方法是不同的。您的标题是指第一种情况,但是从您的代码中可以看出您正在使用表格。

对于命名范围的情况,您可以像这样更改范围(即更改列数):

With ThisWorkbook.Names.Item("testTable")
    .RefersTo = .RefersToRange.Resize(, newColumnsCount)
End With

对于表格(ListObject)的情况,这似乎是你的情况,你可以像这样改变列数:

  Dim testTable As ListObject             ' <-- Declare as ListObject
  Set testTable = Test.ListObjects("testTable")
  ' Or Set testTable = Test.Range("testTable")

  'Some code
  ' ....

   testTable.Resize testTable.Range.Resize(, newColumnsCount) ' <-- resize number of cols

答案 1 :(得分:0)

假设您在表(ListObject)中的某些列上使用了其他代码.ClearContents,那么最初说的是:

OriginalTable

然后让我们说一些代码清除列D和I(标题C和H)的内容:

2 Cols ClearContents

运行下面的代码将从表中删除这些列(通过删除整个列)。然后,您可以使用列表表.DataBodyRange仅访问表数据。

Option Explicit

Sub TableResize()
    Dim oTable As ListObject, oRng As Range, sColsToDelete As String
    Set oTable = ActiveSheet.ListObjects("Table1")
    For Each oRng In oTable.HeaderRowRange
        Debug.Print oRng.Address(0, 0), oRng.Value
        If oRng.Value Like "Column*" Then
            Debug.Print "Column " & oRng.Column & " to be deleted"
            ' Note order to delete is reversed!
            If Len(sColsToDelete) > 0 Then sColsToDelete = "," & sColsToDelete
            sColsToDelete = oRng.Column & sColsToDelete
        End If
    Next
    If Len(sColsToDelete) > 0 Then DeleteCol sColsToDelete
    ' Example to access the data ranges
    For Each oRng In oTable.DataBodyRange
        Debug.Print oRng.Address(0, 0), oRng.Value
    Next
    Set oTable = Nothing
End Sub

Private Sub DeleteCol(sList As String)
    Dim oItem As Variant
    For Each oItem In Split(sList, ",")
        ActiveSheet.Columns(CLng(oItem)).Delete
    Next
End Sub

执行TableResize的结果:
Result