选择Excel中变量范围内的所有非空白单元格进行导出

问题描述 投票:0回答:1

我有一个 Excel 数据集。从C列开始,它有从C2到每次使用时都会变化的数字的连续数据。

对于 D 列中的每一行连续数据,我也想选择 C-J 列的行。我正在尝试选择此数据以使用该数据创建新的 Excel 工作簿。

当我跑步时:

Dim lastVal As Range, sht As Worksheet

Set sht = Sheets("sheet1")

Set lastVal = sht.Columns(4).Find("*", sht.Cells(1, 48), xlValues, _
                                xlPart, xlByColumns, xlPrevious)

Debug.Print lastVal.Address

sht.Range("C2", lastVal).Resize(, 48).Select
selection.copy

Set Objexcel = CreateObject("Excel.application")
objexcel.visible = True
objexcel.cells(1, 1).paste

我得到:

运行时错误“13”:类型不匹配

Set LastVal
线上。

excel vba select
1个回答
0
投票

类似这样的:

Sub Tester()
    Dim sht As Worksheet, wb As Workbook, shtNew As Worksheet
    
    Set sht = ThisWorkbook.Sheets("sheet1") 'or activeworkbook
    
    Set wb = Workbooks.Add() 'add new workbook
    Set shtNew = wb.Worksheets(1)

    'copy from Col C, using last row from Col D?
    'not sure if that's really what you want though?
    With sht.Range("C2:J" & sht.Cells(Rows.Count, "D").End(xlUp).Row)
        Debug.Print "copying", .Address
        'straight copy
        .Copy shtNew.Range("A1")
        '...or copy values only
        shtNew.Range("A1").Resize(.Rows.Count, .Columns.Count).Value = .Value
    End With
End Sub

您可以使用任何其他没有空格的列来代替

sht.Cells(Rows.Count, "D")

© www.soinside.com 2019 - 2024. All rights reserved.