2013-09-25 74 views
0

首先從Source工作簿中獲取非空單元格的範圍。然後在目標工作簿中選擇相似範圍的單元格。這怎麼能實現?找出Endxl的範圍是什麼

完整的代碼::

~~~~~~~~~~~

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 

回答

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 
+0

謝謝@Santosh!它的工作是預期的。只有一個問題,如果我的目標範圍需要不是源範圍,那我們該怎麼做?我不想複製Destination.xls的「A2:until end」中的舍入值,而是在「C7:until end」中複製。我們如何才能瞭解源(rng1)的完整範圍?如果我設置了rng2 = .Range(「C7」),那麼只有第一個值會四捨五入,其他的只會被複制。如何獲得所有的四捨五入的值?請說明一點。 – vbastart

+0

@vbastart請看看FormulaR1C1 – Santosh

+0

我已經開始使用FormulaR1C1了,但似乎沒有得到它的控制。在我的代碼中,我應該如何使用它,以便將所有值複製並舍入?我真的不知道該怎麼做。我試過, 設置DestinationRng.FormulaR1C1 =「= R7C9」,但得到一個錯誤的對象是必需的。 :( – vbastart

0

如果您rng1正常工作,你可以這樣來做:

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

Thanx。我的實際代碼如下所示(請參閱編輯部分):我需要考慮源表單中的一系列值,將它們四捨五入到最接近的1000,然後複製到目標表單中,但出現類型不匹配的錯誤(由於diff範圍rng1和rng2)。我是否必須使用循環,如果是,那麼如何?任何幫助,將不勝感激。 – vbastart