使用VBAselect所有非空行和单元格

我是新来的VBA,我一直想弄清楚如何打开一个input文件,并将这些内容复制到我的工作簿上隐藏的工作表,我看到了如何做到这一点,但行数和列数的例子是静态的,我不得不使用3个不同的input文件,其中一个不断变化,尽pipe我一直试图用我的直觉来做这个事情,但我似乎无法find答案。

这是它:

Sub s() ' Get customer workbook... Dim customerBook As Workbook Dim filter As String Dim caption As String Dim customerFilename As String Dim customerWorkbook As Workbook Dim targetWorkbook As Workbook ' make weak assumption that active workbook is the target Set targetWorkbook = Application.ActiveWorkbook ' get the customer workbook filter = "Text files (*.xlsx),*.xlsx" caption = "Please Select an input file " customerFilename = Application.GetOpenFilename(filter, , caption) Set customerWorkbook = Application.Workbooks.Open(customerFilename) ' copy data from customer to target workbook Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) Dim sourceSheet As Worksheet Set sourceSheet = customerWorkbook.Worksheets(1) Dim lastRow As Long lastRow = sourceSheet.Range("A" & Rows.Count).End(xlUp).Row Dim lastColumn As Long lastColumn = sourceSheet.Cells(1, Columns.Count).End(xlToLeft).Column targetSheet.Range("A1:A" & lastRow).Value = sourceSheet.Range("A1:A" & lastRow).Value ' Close customer workbook customerWorkbook.Close End Sub 

我正在使用EXCEL 2007

如果这是一个愚蠢的noob问题,我提前道歉,但我真的放弃,不知道还有什么可以做的工作。

问题是我不知道如何使它select第一到最后一行和第一个到最后一个单元格(非空白:单元格和行)

试过这个:

 targetSheet.Range("A1:A" & lastRow).End(xlUp).Value = sourceSheet.Range("A1:A" & lastRow).End(xlUp).Value and this targetSheet.Range("A1:A" & lastRow).End(xlRight).Value = sourceSheet.Range("A1:A" & lastRow).End(xlRight).Value 

那么这样的事情呢?

 SourceSheet.UsedRange.Copy TargetSheet.Range("A1")