抵消动态范围的数据

时间:2016-06-07 21:48:24

标签: excel vba excel-vba offset dynamic-values

我遇到了一些看似非常基本的问题。我对vba的体验基本上没什么。我有一个电子表格,其中包含使用我制作的脚本从某些csv文件导入的数据。脚本读入数据然后创建主电子表格或覆盖以前的主电子表格。我想在同一个脚本中将这些数据移到一列。每次更新电子表格时,需要移动的数据范围会随着更多数据的添加而变化。我在代码的末尾包含以下内容来执行此操作,但我无法使其工作。

Set myRange = Range(Cells(1, 1).Address(), Cells(lastRow, lastColumn).Address())

Range("myRange").Offset(,1)

我做错了什么?

编辑:这就是我现在拥有的。我一直在第14行遇到“运行时错误1004”。

Dim myRange As Range
Dim DefPath As String
Dim lastRow As Long
Dim lastColumn As Long

Dim lRow As Long
Dim lCol As Long

DefPath = Application.DefaultFilePath
Workbooks.Open Filename:=DefPath & "\SEM Master File"

lRow = Cells(Rows.Count, 1).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set myRange = Range(Cells(1, 1), Cells(lastRow, lastColumn))
myRange.Offset(, lastColumn).Value = myRange.Value

第二次编辑:这是我到目前为止所拥有的。它编译并运行,但不是像我预期的那样将所有内容移动到一列上,而是创建列的副本并将其放在电子表格中已存在的数据旁边的列中。

Sub Offset_Data()
Dim myRange As Range
Dim DefPath As String
Dim lastRow As Long
Dim lastColumn As Long

DefPath = Application.DefaultFilePath
Workbooks.Open ("SEM Master File.xlsx")

lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
Set myRange = Range(Cells(1, 1), Cells(lastRow, lastColumn))
myRange.Offset(, lastColumn).Value = myRange.Value
End Sub

1 个答案:

答案 0 :(得分:1)

Sub Offset_Data()
Dim myRange As Range
Dim DefPath As String
Dim lastRow As Long
Dim lastColumn As Long

DefPath = Application.DefaultFilePath
Workbooks.Open ("SEM Master File.xlsx")

lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
Set myRange = Range(Cells(1, 1), Cells(lastRow, lastColumn))
myRange.Offset(, lastColumn).Value = myRange.Value
myRange.ClearContents
End Sub