VBA从字符串/单元格

时间:2017-03-10 11:09:23

标签: excel string vba excel-vba numbers

我希望你能提供帮助。

我有一段代码正在删除列G中单元格中的所有文本。我需要的是此代码而不是删除文本我希望它删除数字,我只想要它要删除字符串/单元格开头的数字我希望保持相同的其余数据。

我附上图片PIC.1用于投注理解。

PIC1 enter image description here

我目前拥有的代码,我希望可以修改如下,并且一如既往地提供任何帮助非常感谢

代码

Sub RemoveNonDigits()
  Dim X As Long, Z As Long, LastRow As Long, CellVal As String
  Const StartRow As Long = 1
  Const DataColumn As String = "G"
  Application.ScreenUpdating = False
  LastRow = Cells(Rows.Count, DataColumn).End(xlUp).Row
  For X = StartRow To LastRow
    CellVal = Cells(X, DataColumn)
    For Z = 1 To Len(CellVal)
      If Mid(CellVal, Z, 1) Like "[!0-9]" Then Mid(CellVal, Z, 1) = " "
    Next
    With Cells(X, DataColumn)
      .NumberFormat = "@"
      .Value = Replace(CellVal, " ", "")
    End With
  Next
  Application.ScreenUpdating = True
End Sub

5 个答案:

答案 0 :(得分:5)

CellVal = LTrimDigits(Cells(X, DataColumn))

有了这个效率:

Public Function LTrimDigits(value As String) As String
    Dim i As Long
    For i = 1 To Len(value) '//loop each char
        Select Case Mid$(value, i, 1) '//examine current char
            Case "0" To "9" '//permitted chars
            Case Else: Exit For '// i is the cut off point
        End Select
    Next
    LTrimDigits = Mid$(value, i) '//strip lead
End Function

答案 1 :(得分:3)

请参阅以下修改后的代码:

Sub RemoveNonDigits()
  Dim X As Long, Z As Long, LastRow As Long, CellVal As String
  Const StartRow As Long = 1
  Const DataColumn As String = "G"
  Application.ScreenUpdating = False
  LastRow = Cells(Rows.Count, DataColumn).End(xlUp).Row
  For X = StartRow To LastRow
    CellVal = Cells(X, DataColumn)
    While IsNumeric(Left(CellVal, 1))   ' Here
      CellVal = Mid(CellVal, 2)         ' all digits at the start 
    Wend                                ' are removed
    Cells(X, DataColumn) = Trim(CellVal)
  Next
  Application.ScreenUpdating = True
End Sub

也就是说,虽然CellVal中的起始字符是数字,但是从第二个字符开始获取子字符串,然后继续直到不匹配。

答案 2 :(得分:2)

此函数将从字符串中删除前导数字和空格

Sub RemoveNonDigits()
    Dim X As Long, LastRow As Long, CellVal As String
    Const StartRow As Long = 1
    Const DataColumn As String = "G"
    Application.ScreenUpdating = False
    LastRow = Cells(Rows.Count, DataColumn).End(xlUp).Row
    For X = StartRow To LastRow
        CellVal = Cells(X, DataColumn).Value
        ' ----------------------------------------
        CellVal = RemoveLeadingDigits(CellVal)
        ' ----------------------------------------
    Next
    Application.ScreenUpdating = True
End Sub

您可以通过

从代码中调用它
With ThisWorkbook.Sheets("YourSheet")

关于您的代码的说明:

你应该完全符合你的细胞资格。例如,将整个循环部分包裹在.Cells(row, col)中,然后使用Cells(row, col)访问单元格而不只是{{1}}。

答案 3 :(得分:2)

有点hacky较短的替代方案(假设所有值都以整数开头)

using UnityEngine;
using Assets.Helpers; //DONT COPY
using System;
using System.Collections;

public class TileManager : MonoBehaviour {
[SerializeField]
private Settings _settings;

[SerializeField]
private Transform target;

[SerializeField]
private Texture2D texture;
private GameObject tile;

[SerializeField]//DONT COPY
private GameObject service;//DONT COPY

private float oldLat = 0f, oldLon = 0f;
private float lat = 0f, lon = 0f;

public PokemonManager pokeManager;

public Animator animator;

public float getLat {
    get {
        return lat;
    }
}

public float getLon {
    get { 
        return lon;
    }
}

IEnumerator Start()
{
    //Waiting for user to turn on GPS
    while (!Input.location.isEnabledByUser) {
        print ("Activate gps");
        yield return new WaitForSeconds (1f);
    }

    Input.location.Start(10f, 5f);

    //Waiting for GPS service to work
    int maxWait = 20;
    while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
    {
        yield return new WaitForSeconds(1);
        maxWait--;
    }

    //GPS Service failed to work so break
    //Break - Go out and end the function Start()
    if (maxWait < 1)
    {
        print("Timed out");
        yield break;
    }

    if (Input.location.status == LocationServiceStatus.Failed)
    {
        //GPS Service failed to work so break
        //Break - Go out and end the function Start()
        print("Unable to determine device location");
        yield break;
    }
    else
    {
        print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
    }

    //Set latitude and longitude of user's current location
    lat = Input.location.lastData.latitude;
    lon = Input.location.lastData.longitude;

    //Call this coroutine which is responsible for:
    //1. Loading of the map
    //2. Updating of the map
    //StartCoroutine (loadTiles (_settings.zoom));

    while (Input.location.isEnabledByUser) {
        yield return new WaitForSeconds (1f);           
    }

    yield return null;
    StartCoroutine (Start ());
    yield break;
}

public IEnumerator loadTiles(int zoom) {
    int size = _settings.size;
    string key = _settings.key;
    string style = _settings.style;

    lat = Input.location.lastData.latitude;
    lon = Input.location.lastData.longitude;

    //string url = String.Format ("https://api.mapbox.com/v4/mapbox.{5}/{0},{1},{2}/{3}x{3}@2x.png?access_token={4}", lon, lat, zoom, size, key, style);
    string url = String.Format("https://api.mapbox.com/styles/v1/{5}/static/{0},{1},{2}/{3}x{3}@2x?access_token={4}", lon, lat, zoom, size, key, style);
    WWW www = null;

    www = new WWW (url);
    yield return www;

    texture = www.texture;

    if (tile == null) {
        tile = GameObject.CreatePrimitive (PrimitiveType.Plane);
        tile.name = "Tile " + lat + "" + lon;
        tile.transform.localScale = Vector3.one * _settings.scale;
        tile.GetComponent<Renderer> ().material = _settings.material;
        tile.transform.parent = transform;
    }

    if (oldLat != 0 && oldLon != 0) {
        float x, y;
        Vector3 position = Vector3.zero;

        geodeticOffsetInv (lat * Mathf.Deg2Rad, lon * Mathf.Deg2Rad, oldLat * Mathf.Deg2Rad, oldLon * Mathf.Deg2Rad, out x, out y);

        if ((oldLat - lat) < 0 && (oldLon - lon) > 0 || (oldLat - lat) > 0 && (oldLon - lon) < 0) {
            position = new Vector3 (x, .5f, y);
        } else {
            position = new Vector3 (-x, .5f, -y);
        }

        position.x *= 0.300122f;
        position.z *= 0.123043f;

        target.position = position;
    }

    pokeManager.UpdatePokemonPosition ();

    tile.GetComponent<Renderer> ().material.mainTexture = texture;

    yield return new WaitForSeconds (1f);

    oldLat = lat;
    oldLon = lon;

    while (oldLat == lat && oldLon == lon) {
        lat = Input.location.lastData.latitude;
        lon = Input.location.lastData.longitude;
        yield return new WaitForSeconds (0.5f);
    }

    yield return new WaitUntil ( () => (oldLat != lat || oldLon != lon) );

    yield return null;
    StartCoroutine (loadTiles (_settings.zoom));
    yield break;
}


//SOURCE: http://stackoverflow.com/questions/4953150/convert-lat-longs-to-x-y-co-ordinates

float GD_semiMajorAxis = 6378137.000000f;
float GD_TranMercB     = 6356752.314245f;
float GD_geocentF      = 0.003352810664f;

void geodeticOffsetInv( float refLat, float refLon, float lat, float lon,out float xOffset, out float yOffset)
{
    float a = GD_semiMajorAxis;
    float b = GD_TranMercB;
    float f = GD_geocentF;

    float L = lon - refLon;
    float U1    = Mathf.Atan((1-f) * Mathf.Tan(refLat));
    float U2    = Mathf.Atan((1-f) * Mathf.Tan(lat));
    float sinU1 = Mathf.Sin(U1);
    float cosU1 = Mathf.Cos(U1);
    float sinU2 = Mathf.Sin(U2);
    float cosU2 = Mathf.Cos(U2);

    float lambda = L;
    float lambdaP;
    float sinSigma;
    float sigma;
    float cosSigma;
    float cosSqAlpha;
    float cos2SigmaM;
    float sinLambda;
    float cosLambda;
    float sinAlpha;
    int iterLimit = 100;
    do {
        sinLambda = Mathf.Sin(lambda);
        cosLambda = Mathf.Cos(lambda);
        sinSigma = Mathf.Sqrt((cosU2*sinLambda) * (cosU2*sinLambda) +
            (cosU1*sinU2-sinU1*cosU2*cosLambda) *
            (cosU1*sinU2-sinU1*cosU2*cosLambda) );
        if (sinSigma==0)
        {
            xOffset = 0.0f;
            yOffset = 0.0f;
            return ;  // co-incident points
        }
        cosSigma    = sinU1*sinU2 + cosU1*cosU2*cosLambda;
        sigma       = Mathf.Atan2(sinSigma, cosSigma);
        sinAlpha    = cosU1 * cosU2 * sinLambda / sinSigma;
        cosSqAlpha  = 1 - sinAlpha*sinAlpha;
        cos2SigmaM  = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
        if (cos2SigmaM != cos2SigmaM) //isNaN
        {
            cos2SigmaM = 0;  // equatorial line: cosSqAlpha=0 (§6)
        }
        float C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
        lambdaP = lambda;
        lambda = L + (1-C) * f * sinAlpha *
            (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
    } while (Mathf.Abs(lambda-lambdaP) > 1e-12 && --iterLimit>0);

    if (iterLimit==0)
    {
        xOffset = 0.0f;
        yOffset = 0.0f;
        return;  // formula failed to converge
    }

    float uSq  = cosSqAlpha * (a*a - b*b) / (b*b);
    float A    = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
    float B    = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
    float deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
        B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
    float s = b*A*(sigma-deltaSigma);

    float bearing = Mathf.Atan2(cosU2*sinLambda,  cosU1*sinU2-sinU1*cosU2*cosLambda);
    xOffset = Mathf.Sin(bearing)*s;
    yOffset = Mathf.Cos(bearing)*s;
}

void Update() {
    //service.SetActive (!Input.location.isEnabledByUser);//DONT COPY
    target.position = Vector3.Lerp (target.position, new Vector3 (0,.5f, 0), 2.0f * Time.deltaTime);
}

[Serializable]
public class Settings {
    [SerializeField]
    public Vector2 centerPosition;
    [SerializeField]
    public Material material;
    [SerializeField]
    public int zoom = 18;
    [SerializeField]
    public int size = 640;
    [SerializeField]
    public float scale = 1f;
    [SerializeField]
    public int range = 1;
    [SerializeField]
    public string key = "KEY_HERE";
    [SerializeField]
    public string style = "emerald";
}
}

答案 4 :(得分:1)

我认为这是一个简单的改变:

For X = StartRow To LastRow
    Cells(X, DataColumn).Formular1c1 = Application.Trim(Replace(Cells(X, DataColumn).Text, Val(Cells(X, DataColumn).Text), ""))
Next X

将解决您的问题...