我需要確保每列中的所有單元格都具有該列的目標長度。當目標長度大于給定單元格中字串值的實際長度時,必須在前面添加x個0,以使字串的長度等于目標。
到目前為止,我有這個代碼:
Dim row_counter1 As Long
Dim char1 As Integer
Dim char_dif1 As Integer
Dim char_targ1 As Integer
char_targ1 = 2
For row_counter1 = 2 To last_row_index(output, 1)
char1 = Len(output.Cells(row_counter1, 1))
char_dif1 = char_targ1 - char1
Debug.Print char_dif1
Next row_counter1
last_row_index 是一個簡單的 UDF,使用 End.xlUp 方法查找最后一個連續行索引。回圈運行良好,給了我整數格式的差異。
取那個整數并將其變成 0 并放在 cell.value 前面是我無法解決的問題。我已經看到了 Python 類似問題的解決方案,但是我對編碼非常陌生,并且在理解該程序時遇到了困難。
uj5u.com熱心網友回復:
在這樣的單元格中,例如 10 位數的長度:
=RIGHT(“0000000000000”&A1,10)
uj5u.com熱心網友回復:
請嘗試下一個功能:
Function addZero(rng As Range, strLength As Long) As Variant
rng.NumberFormat = "@"
addZero = Evaluate("RIGHT(""" & String(strLength, "0") & """&" & rng.Address & "," & strLength & ")")
End Function
可以通過以下方式從您的(改編的)代碼中呼叫它:
Sub PlaceZero()
Dim sh As Worksheet, rng As Range, lastR As Long
Dim char_targ1 As Long: char_targ1 = 5
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
Set rng = sh.Range("A2:A" & lastR)
rng.value = addZero(rng, char_targ1)
End Sub
無需迭代使用Evaluate...
但是,如果您嘗試將char_targ1長度設定為低于現有字串,那么它char_targ1當然會被截斷為長度。
預先檢查每個單元格中的非零字符是否小于“char_targ1 Sub” , the next way can be used (directly in the calling ):
Dim arr, MTCH
arr = Evaluate("TRANSPOSE(IF(LEN(SUBSTITUTE(" & rng.Address(0, 0) & ",""0"",""""))<" & char_targ1 & ",""x"",""""))")
MTCH = Application.match("x", arr, 0)
If IsNumeric(MTCH) Then MsgBox "There are strings with less characters (except zero) than :" & char_targ1 & "...": Exit Sub
它應該放在代碼行之前:
rng.value = addZero(rng, char_targ1)
但它也計算原始字串中現有的零字符。我的意思是,不僅前導零字符...
uj5u.com熱心網友回復:
REPT (文本, number_times )
例子
application.WorksheetFunction.Rept(0,10)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492088.html
下一篇:VBA公式不計算和動態參考
