2016-06-27 59 views
1

我想要使用輸入框要求用戶輸入數據中使用的帳戶號碼的長度,這可能會有所不同,然後拆分列基於用戶輸入的固定寬度。在我的研究中,我只能找到在分開的列中插入兩個len公式,然後刪除原始公式。如果可能,我試圖避免這種情況。輸入框爲固定寬度的列的文本 - Excel崩潰

這裏是我目前擁有的代碼:

Dim Message, Title, Default, MyValue 
    Message = "Input the character length of the account numbers." 
    Title = "Account Number Length" 
    Default = "4" 
    MyValue = InputBox(Message, Title, Default) 

    'Split Account numbers 
    Columns("B:B").Select 
    Selection.TextToColumns Destination:=Range("B1"), DataType:=xlFixedWidth, _ 
     OtherChar:=":", FieldInfo:=Array(Array(0, 1), Array(MyValue, 1)), _ 
     TrailingMinusNumbers:=True 

當我嘗試使用MyValue作爲FieldInfo:=Array(Array(0, 1), Array(MyValue, 1))的一部分擅長崩潰。有沒有一種方法來定義或輸入它,以便將輸入值作爲值插入到Array(MyValue, 1)中,而不會導致Excel崩潰?

例如,如果帳號長度是4,那麼返回值應該是Array(4,1)。

回答

2
Sub test() 

    Dim Message, Title, Default, MyValue 

    Dim rngRaw As Range 


    Message = "Input the character length of the account numbers." 
    Title = "Account Number Length" 

    Default = "4" 
    '/ Pass as numeric 
    MyValue = Val(InputBox(Message, Title, Default)) 

    'Split Account numbers 
    'Columns("B:B").Select 

    'Instead of full column try with data range. Avoids crash. 
    Set rngRaw = Sheet1.UsedRange.Columns(2) '/ Change as per your actual data. 

    rngRaw.TextToColumns Destination:=rngRaw.cells(1,1), DataType:=xlFixedWidth, _ 
     OtherChar:=":", FieldInfo:=Array(Array(0, 1), Array(MyValue, 1)), _ 
     TrailingMinusNumbers:=True 

End Sub 

「/更新爲每個用戶在評論 查詢」 //另一個版本do循環。我不建議這雖然

Sub test() 

    Dim Message, Title, Default, MyValue As String 
    Dim rngRaw As Range 

    Dim lDelLen  As Long 

    Message = "Input the character length of the account numbers." 
    Title = "Account Number Length" 

    Default = "4" 
    '/ Pass as numeric 
    MyValue = "Foo" 

    Do 
     MyValue = InputBox(Message, Title, Default) 
     'If a user presses cancel then MyValue 
     ' is a vbNullString and we should allow the 
     ' user to abort the entire sub 
     If MyValue = vbNullString Then Exit Sub 
     If IsNumeric(MyValue) Then Exit Do 
    Loop 

    lDelLen = Val(MyValue) 

    'Split Account numbers 
    'Columns("B:B").Select 

    'Instead of full column try with data range. Avoids crash. 
    Set rngRaw = Sheet1.UsedRange.Columns(2) '/ Change as per your actual data. 

    rngRaw.TextToColumns Destination:=rngRaw.Cells(1, 1), DataType:=xlFixedWidth, _ 
     OtherChar:=":", FieldInfo:=Array(Array(0, 1), Array(lDelLen, 1)), _ 
     TrailingMinusNumbers:=True 

End Sub 
+2

只是作爲一個附加的改進,你可能要考慮宣佈'MyValue'作爲一個字符串,並檢查'如果則IsNumeric(myvalue的)Then'。以防萬一,並採取良好措施。 – Ralph

+0

@Ralph我得到了msgbox彈出,但它結束了子,如果它出錯。宏插入表單和列等,只是再次運行會導致錯誤。有沒有辦法將msgbox錯誤循環回輸入屏幕? – Excellerator

+0

@Cyboashu謝謝! – Excellerator