2016-03-19 80 views
1

我想從VBA切換到VSTO,但我遇到一些我不熟悉的錯誤,當我嘗試調整範圍。VSTO:Excel調整範圍在vb.net

我有下面的代碼,最終應該能夠在x行中分割一系列單元格。

我已經在VSTO中創建了一個項目作爲加載項。當我通過在Excel中按下按鈕來運行代碼時,Visual Studo給了我一個「COMExeption未被用戶代碼處理」並且它高亮顯示了最後一行,我嘗試調整其大小並輸出範圍。

我在做什麼錯?

Private Sub Button1_Click(sender As Object, e As RibbonControlEventArgs) Handles Button1.Click 

    Dim sheet As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet 
    Dim inputrange As Excel.Range 
    'Dim cell As Excel.Range 
    Dim numberOfOutputRows As Long 
    Dim numberOfOutPutColumns As Long 
    Dim outputRange As Excel.Range 
    Dim inputArray(0, 0) As Long 
    Dim i As Long 
    Dim iRow As Long 
    Dim iCol As Long 
    Dim numberOfCells As Long 
    Dim arrayInputValue As Excel.Range 
    Dim val As Object 


    inputrange = CType(sheet.Application.InputBox("select range",,,,,,, Type:=8), Excel.Range) 

    'Dim myRange As Excel.Range 

    numberOfOutputRows = InputBox("You have " & inputrange.Count & " cells. Enter the number of rows you want to split up in") 

    numberOfOutPutColumns = inputrange.Cells.Count/numberOfOutputRows 

    outputRange = CType(sheet.Application.InputBox("Output to single cell",,,,,,, Type:=8), Excel.Range) 

    inputrange = inputrange.Columns(1) 

    ReDim inputArray(0 To numberOfOutputRows, 0 To numberOfOutPutColumns + 1) 

    numberOfCells = inputrange.Cells.Count - 1 

    For i = 0 To numberOfCells 
     arrayInputValue = CType(inputrange.Cells(i + 1), Excel.Range) 
     val = arrayInputValue.value() 
     iRow = i Mod numberOfOutputRows 
     iCol = Int(i/numberOfOutputRows) 
     inputArray(iRow + 1, iCol + 1) = val ' arrayInputValue 
    Next i 

    outputRange.Resize(RowSize:=UBound(inputArray, 1), ColumnSize:=UBound(inputArray, 2)).Value = inputArray 

回答

0

您必須聲明你的輸出數組對象,而不是長期

Dim inputArray(0, 0) As Object 

VSTO讀取/從/到細胞對象寫入數據。

+0

謝謝。看起來我還有其他一些問題,因爲我放棄了inputArray中填充的一些值 - 你能幫忙嗎? – Jmorte13

+0

它應該像在VBA中一樣工作。你有沒有在VBA中嘗試過(稍做修改)?你知道你可以在Visual Studio中調試你的代碼,看看你的數組中究竟寫了什麼,對吧? 我沒有嘗試過它是真的,讓我知道如果你不知道,我會盡力幫助你 – PetLahev

+0

我已經在VBA中試過它,它的工作原理非常完美。我有一些輕微的修改艱難。我不熟悉debuggen Visual Studio,這是如何完成的?我將在這裏粘貼VBA代碼,但我沒有足夠的字符。 – Jmorte13