找出Endxl的范围是什么

时间:2013-09-25 21:38:44

标签: excel-vba vba excel

首先从Source工作簿中获取非空单元格的范围。然后在目标工作簿中选择类似的单元格范围。如何实现这一目标?

完整代码::

~~~~~~~~~~~

Public Sub ConvertTo_K()

Dim rng1 As Range 

Dim rng2 As Range 

Set rng1 = Workbooks("Source.xls").Worksheets("Source").Range(Cells(2, "A"), Cells(Rows.Count, "A").End(xlUp).Resize(, 1)) 

Set rng2 = Workbooks("Destination.xls").Worksheets("Destination").Range(rng1.Address)

rng2.Value = Round(rng1.Value / 1000, 2)

 'At this point, an error message of Type Mismatch pops up (Due to different ranges of rng1 and rng2). Do i have to use a loop? How to do that? 

End Sub

2 个答案:

答案 0 :(得分:0)

如果您的rng1工作正常,您可以这样做:

set rng2 = Workbooks("Destination.xls").Worksheets("Destination").Range(rng1.address)

答案 1 :(得分:0)

Round(rng1.Value / 1000, 2)无效,因为rng1是范围的集合,可以通过rng1.Cells(1).value

访问

rng1.Value无效。

您可以循环遍历rng2的每个单元格并应用圆形公式。

Public Sub ConvertTo_K()

    Dim rng1 As Range
    Dim rng2 As Range
    Dim RoundRange As Range
    Dim rngVal As Double

    Dim SourceWkb As Workbook
    Set SourceWkb = Workbooks("Source.xls")

    Dim SourceSht As Worksheet
    Set SourceSht = SourceWkb.Worksheets("Source")

    With SourceSht
     Set rng1 = .Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp).Resize(, 1))
    End With

    Dim DestinWkb As Workbook
    Set DestinWkb = ThisWorkbook  'Workbooks("Destination.xls")

    Dim DestinSht As Worksheet
    Set DestinSht = DestinWkb.Worksheets("Destination")

    With DestinSht
          Set rng2 = .Range(rng1.Address)
    End With

     'rng2.Value = Round(rng1.Value / 1000, 2) This wont work

     rng1.Copy rng2

     For Each cell In rng2
        cell.Value = Round(cell / 1000, 2)
     Next
End Sub