简体   繁体   English

在此Workbook.Sheets(1).Range(newRange).Value中无法识别newRange As Range。

[英]newRange As Range is not recognized in ThisWorkbook.Sheets(1).Range(newRange).Value

I want to assign values from one spreadsheet to this one and it works when I give the range of cells in the macro (like Range("A3:J4")), but not when I try to manually select the destination cells. 我想将一个电子表格中的值分配给该电子表格,当我在宏中指定单元格的范围(如Range(“ A3:J4”))时,它可以工作,但是当我尝试手动选择目标单元格时,它不起作用。

So this works: 所以这工作:

Private Sub CommandButton1_Click()
Dim OpenFileName As String
Dim wb As Workbook
'Select and Open workbook

OpenFileName = Application.GetOpenFilename("DATA,*.txt")
If OpenFileName = "False" Then Exit Sub
    Set wb = Workbooks.Open(OpenFileName)

    'Get data EXAMPLE    
    ThisWorkbook.Sheets(5).Range("A3:J4").Value = wb.Sheets(1).Range("A3:J4").Value
    wb.Close

But this doesn't work: 但这不起作用:

Private Sub CommandButton1_Click()
Dim OpenFileName As String
Dim wb As Workbook
'Select and Open workbook

OpenFileName = Application.GetOpenFilename("DATA,*.txt")
If OpenFileName = "False" Then Exit Sub
    Set wb = Workbooks.Open(OpenFileName)

    Dim newRange As Range
    Set newRange = Range(ActiveCell, ActiveCell.Offset(1, 9))

    'Get data EXAMPLE  
    ThisWorkbook.Sheets(5).Range(newRange).Value = wb.Sheets(1).Range("A3:J4").Value
    wb.Close

In the second instance, you are treating newRange as if it was a string var of the Range.Address property . 在第二个实例中,您将newRange视为是Range.Address属性的字符串var。 You can use it directly. 您可以直接使用它。

'this assumes that 'newRange' is on Sheets(5)
ThisWorkbook.Sheets(5).newRange.Value = wb.Sheets(1).Range("A3").Resize(newRange.Rows.Count, newRange.Columns.Count).Value
'alternative use as the cell range address
ThisWorkbook.Sheets(5).Range(newRange.address).Value = wb.Sheets(1).Range("A3").Resize(newRange.Rows.Count, newRange.Columns.Count).Value

When using direct value transfer, the ranges have to be the same size. 使用直接值转移时,范围必须相同。

I think you're looking for the Selection -property? 我认为您正在寻找Selection属性? Try 尝试

Set newRange = Selection

For more info: https://msdn.microsoft.com/en-us/library/office/ff840834.aspx 有关更多信息: https : //msdn.microsoft.com/zh-cn/library/office/ff840834.aspx

Afterwards reference the newRange.address on the other sheet: 然后,在另一张纸上引用newRange.address:

Worksheets("TargetSheetName").Range(newRange.address)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM