簡體   English   中英

VBA 根據值更改單元格格式

[英]VBA Change Cell formatting based on value

我想知道如何使用 VBA 自動格式化輸入值的單元格。我實際上將數字分為 3 類:百分比、小數字(-1000 - 1000)和大數字。

我希望以 2 位小數和 % 符號顯示百分比。 小數也有 2 位小數。 大數字四舍五入到最接近的 integer,有數千個分隔符。

我有 VBA 中的條件,但是如果單元格值發生變化,我希望代碼重新格式化單元格,並且知道如何做到這一點。 例如,如果我將一個值為“50,000”的單元格更改為 60%,那么它應該顯示為“60.00%”。 到目前為止,我所擁有的是對現有單元格值應用格式的代碼。

 Sub myNumberFormat() Dim cel As Range Dim selectedRange As Range Set selectedRange = Selection For Each cel In selectedRange.Cells If Not CStr(cel.Text) Like "*%*" Then If Not IsEmpty(cel) Then If cel.Value < 1000 And cel.Value > -1000 Then cel.NumberFormat = "_(#,##0.00_);_(-#,##0.00_);_(""-""??_)" Else cel.NumberFormat = "_(#,##0_);_((#,##0);_(""-""??_)" End If End If Else cel.NumberFormat = "0.00%" End If Next cel End Sub

如果這是最好的代碼,我也知道。 我是 VBA 的新手,我主要在谷歌上搜索點點滴滴。 非常感謝一些幫助和提示,因為我厭倦了格式化東西:)。 謝謝

工作表更改:應用單元格格式

  • 這是一個單列的簡單示例,在這種特殊情況下,范圍是從A2到列A中最底部的單元格。 但是您可以選擇任何合理的單元格地址。 在您手動更改(輸入、復制/粘貼或使用 VBA 寫入)其值的任何單元格中,該單元格將根據您的“重新排列”過程ApplyMySpecialNumberFormat進行格式化。
  • 請注意,這會自動工作,只需將代碼復制到相應的模塊並開始將數據輸入到范圍的單元格中以查看它的工作原理。

工作表模塊,例如Sheet1

 Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) ' Define constants. Const FirstCellAddress As String = "A2" ' adjust to any reasonable cell ' Reference the source column range eg 'A2:ALastWorksheetRow'. Dim srg As Range ' With Me.Range(FirstCellAddress) Set srg =.Resize(Me.Rows.Count -.Row + 1) End With ' Reference the cells of the source range that have changed. Dim irg As Range: Set irg = Intersect(srg, Target) If irg Is Nothing Then Exit Sub ' no source range cells changed; exit ' At least one cell was changed: ApplyMySpecialNumberFormat irg End Sub

標准模塊,例如Module1

 Option Explicit Sub ApplyMySpecialNumberFormat(ByVal rg As Range) Dim cel As Range For Each cel In rg.Cells If CStr(cel.Text) Like "*%*" Then cel.NumberFormat = "0.00%" Else If VarType(cel) = vbDouble Then ' is a number If cel.Value < 1000 And cel.Value > -1000 Then cel.NumberFormat = "_(#,##0.00_);_(-#,##0.00_);_(""-""??_)" Else cel.NumberFormat = "_(#,##0_);_((#,##0);_(""-""??_)" End If End If End If Next cel End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM