在VBA中将整数变量转换为带有前导零的字符串 [英] convert an integer variable to a string with leading zeros in VBA

查看:161
本文介绍了在VBA中将整数变量转换为带有前导零的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于初学者来说,有很多与此主题相关的问题.但是,我一直单击的所有语言都是VBA以外的语言,并且我不理解这些语言的语法.

For starters, there are LOTS of questions that have been asked with this topic. However all the ones I kept clicking on were in languages other than VBA and I did not understand the syntax of those languages.

当我进行Google搜索时,我发现

When I did a google search I found this answer which seemed promising. AH FIDDLE STICKS! I just realized that answer for VB and probably explains why its not working in my VBA

情况

我有一个名为DimScale的变量,它是一个整数.我想创建一个名为DimName的字符串,该字符串将以"mm-"开头,并以DimScale的整数开头,并以0开头,以便在"mm-"之后的字符最少.

I have a variable called DimScale that is an integer. I want to create a string called DimName that will start with "mm-" and be following by the integer from DimScale with leading 0s such that there are a minimum of characters after "mm-".

IF DimScale = 25
Then DimName = "mm-0025"

IF DimScale = 235
Then DimName = "mm-0235"

Note Dimscale >=1 and <= 9999

我尝试过的

Dim Dimscale as Integer
Dim Dimension_Style_Name as String

String.Format("{0:0000}", DimScale)

Dimension_Style_Name = DimScale$
Dimension_Style_Name.Format("{0:0000}", DimScale)

我也读过要点,即Dimscale转换为字符串,然后通过添加前导零的循环发送,直到在我的情况下字符串的长度等于整数部分的4个字符为止.

I have read the gist too that Dimscale get converted to a string and then is sent through a loop of adding a leading zero until the length of the string equals the 4 characters in my case for the integer part.

我也看到了IF语句的情况,其中IF Dimscale小于10,然后是"000"&如果Dimscale< 100,则为"00"&.等

I have also seen the case with IF statments where IF Dimscale <10 then "000"& If Dimscale <100 then "00"& etc.

有没有办法像VBA中的VB方法一样做到这一点?

Is there a way to do it like like the VB method in VBA?

推荐答案

也许是:

DimName = "mm-" & format(DimScale,"0000")

根据@MathieuGuindon的宝贵贡献(照常):

As per @MathieuGuindon valuable (as usual) contribution:

Format(完全合格的VBA.Strings.Format)采用Variant参数,并返回Variant-您还可以使用其弟弟Format $,后者采用String并返回String,从而消除了隐式转换方式

这篇关于在VBA中将整数变量转换为带有前导零的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆