簡體   English   中英

如何在導入或復制/粘貼后將單元格中存儲為文本的數字格式化為數字 | excel | VBA | 解決方案

[英]How to format a number stored as text in a cell as a number after import or copy/paste | Excel | VBA | Solution

首先,感謝這里的每一個人,這些帖子幫助我走得更遠。

這讓我頭疼,花了幾天時間解決。 把它貼在這里希望它有幫助。

問題陳述

我必須每周將導出的 CSV 或 Excel 文檔復制或導入到工作 Excel 文檔中。 當我這樣做時,所有數字都存儲為文本,帶有綠色小圖標和警告您數字可能存儲為文本的錯誤符號。

解決這個問題是不可能的。 您可以突出顯示單元格或列並將數字格式設置為數字,但在雙擊每個單元格之前,它仍然不會更改類型。 我嘗試使用 VBA 自動執行此操作但無濟於事。 無論什么“hack”,我都嘗試強制轉換或更改數字格式,但沒有任何“邏輯”起作用。

(我有一些 C++ 編碼經驗,但 VBA 似乎是一個完全不同的野獸!:))

解決方案

僅通過更改單元格編號格式類型就無法嘗試使用 VBA 解決此問題。 我嘗試了很多東西,直到我偶然發現了這篇文章,解決方案二。

關鍵是在設置格式后將單元格值分配給自己。

下面的子例程遍歷工作表,並根據已知字符串是否匹配來修復相鄰單元格中數字的數字格式。 (這是我看到大多數其他菜鳥都在掙扎的問題陳述,因此將其留在這里,希望它可以幫助任何新手入門。)

Sub SelectiveFixRowFormat()
 
Dim longI As Long 'iterator for each row
Dim longLastRow As Long  'max used row in the sheet
Dim strSearchString As String 'String I am searching for that will have to have the number in the column next to it formatted correctly
 
strSearchString = "QuickBrownFox "
 
'find the last row with something in it.
lRow = Cells(Rows.Count, 1).End(xlUp).Row
 
'main For-loop to loop through each cell.
For longI = 1 To lRow
    If Cells(longI, "C") = strSearchString Then 'only if the text matches the offending entry, change formatting
        Cells(longI, "E").NumberFormat = "0" ' This step does nothing to change the appearance. This is where I see most noobs like me stop completely perplexed.
        Cells(longI, "E").Value = Cells(longI, "E").Value ' This step, which seems absolutely meaningless is what actually gets excel to update the cell's formatting from text to number, fix the appearance, and makes all my vlookups work.
        
    End If
       
Next longI
   
End Sub

更簡單地說,如果您需要在復制/粘貼或導入例程后自動設置數字格式,這是一個兩步過程。 您必須分配單元格編號格式,然后他們將單元格值分配給自身以“觸發”更改。

Cells(X,Y).NumberFormat = "0" 'Set Formatting, doesnt "do" anything
Cells(X,Y).Value = Cells(X,Y).Value 'fixes the display and cell value type so that functions can work on numbers.

這似乎是令人尷尬的簡單堅果,我搜索了很長時間,但在任何地方都找不到明確解釋的解決方案。

  1. 在有文本值的工作表上找到一個空白單元格,然后輸入數字 1。
  2. 選擇此單元格並按復制(或 Ctl+C)
  3. 選擇包含文本格式數字的范圍。
  4. 從功能區的主頁選項卡中,單擊粘貼 > 選擇性粘貼。 選中乘法並按確定。

所有文本值都將轉換為數字(乘以 1)。 真實文本不受影響。 當然,同樣的想法也可以使用 VBA 來執行。

暫無
暫無

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

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