![](/img/trans.png)
[英]Error #VALUE with long string in UDF in VBA for output in Excel
[英]New to Excel VBA: #Value error on string creation
抱歉,我認為該錯誤是基本錯誤,但是我不確定自己在做什么錯誤。
我正在嘗試編寫一個函數,該函數需要一個單元格並將紅色標記的字符轉換為小寫字母。 我通過在新變量中重建字符串來實現。
然后返回此重建的字符串。 但是,當我嘗試在字符串中的Excel中使用此函數時,它將返回#Value錯誤。 該代碼沒有編譯錯誤,所以我很茫然。 任何幫助,將不勝感激。
Function Convert_Red(rng As Range)
If (rng.Cells.Count > 1) Then
AcceptOneCell = "Only allow 1 cell"
Exit Function
End If
Dim i As Long
Dim text As String
Dim new_text As String
Dim placeholder As String
text = rng.Cells(1, 1).Value
For i = 1 To Len(text)
If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color vbRed
Then
new_text = new_text + LCase(rng.Cells(1, 1).Characters(Start:=i,
Length:=1))
Else
new_text = new_text + rng.Cells(1, 1).Characters(Start:=i, Length:=1)
End If
i = i + 1
Next
Convert_Red = new_text
End Function
我猜您當前的代碼是什么,因為發布的代碼無法編譯。 我相信您遵循以下條件:
Function Convert_Red(rng As Range)
If (rng.Cells.Count > 1) Then
'Use the correct function name when returning a result
'AcceptOneCell = "Only allow 1 cell"
Convert_Red = "Only allow 1 cell"
Exit Function
End If
Dim i As Long
Dim text As String
Dim new_text As String
Dim placeholder As String
text = rng.Cells(1, 1).Value
For i = 1 To Len(text)
'Fix syntax errors
'If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color vbRed
'Then
If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color = vbRed Then
' 1) Fix syntax errors
' 2) Use & for string concatenation
' 3) A Characters object has no default property - specify Text
'new_text = new_text + LCase(rng.Cells(1, 1).Characters(Start:=i,
'Length:=1))
new_text = new_text & LCase(rng.Cells(1, 1).Characters(Start:=i, Length:=1).Text)
Else
' 1) Use & for string concatenation
' 2) A Characters object has no default property - specify Text
'new_text = new_text + rng.Cells(1, 1).Characters(Start:=i, Length:=1)
new_text = new_text & rng.Cells(1, 1).Characters(Start:=i, Length:=1).Text
End If
'Don't mess with the loop counter
'i = i + 1
Next
Convert_Red = new_text
End Function
請注意,如果源范圍包含公式,數值或日期,則無法使用“ Characters
。
嘗試這個:
Option Explicit
Public Function LCaseReds(rng As Range)
Dim i As Long, ltr As String, adr As String, result As String
Select Case True
Case rng.Cells.Count > 1: result = "Use only one cell"
Case Len(rng.Value2) = 0: result = "Empty cell: '" & rng.Address(False, False) & "'"
Case Else:
For i = 1 To Len(rng)
With rng.Characters(Start:=i, Length:=1)
ltr = .Text
result = result + IIf(.Font.Color = vbRed, LCase(ltr), ltr)
End With
Next
End Select
LCaseReds = result
End Function
請注意,您仍然會獲得#Value! 使用多個區域(C3,E3)時
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.