在VBA中创建号码前缀

发布于 2024-11-03 13:16:12 字数 284 浏览 3 评论 0原文

我有几个版本号需要从中创建文件夹。因此,我们可以说 {4, 12, 534}。由此,我需要创建可以相应排序的文件夹;

\004\..
\012\..
\534\..

因此,我需要的是获取最高的数字,然后查看每个文件夹名称需要多少个填充零,以便在创建它们后对它们进行正确的排序。

如何使用 VBA (Excel) 执行此操作?我尝试将它们转换为字符串,然后处理字符串操作,但这并没有完全解决。

我希望有人对此有个好主意......

I have several revision numbers I need to create folders from. So, lets say {4, 12, 534}. From this, I need to create folders that can be sorted accordingly;

\004\..
\012\..
\534\..

So, what I need to is to get the highest number and then see, how many filling zeros I need for every foldername so they are sorted correct after creating them.

How can I do this using VBA (Excel)? I tried converting them to strings and then dealing around with String operations, but this didn't quite work out.

I hope someone has a nice idea for this...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苄①跕圉湢 2024-11-10 13:16:12

最简单的方法是使用 Format (或 Format$):

dim s As String

    s = Format$(revNum, "000")

使用 "000" 作为“格式字符串”告诉函数用前导填充零,而 "###" 告诉它不要填充。函数版本之间的区别在于返回类型:Format 返回 Variant (String),而 Format$ 返回实际的 String。

The simplest way is with Format (or Format$):

dim s As String

    s = Format$(revNum, "000")

Using "000" as the "format string" tells the function to pad with leading zeros, whereas "###" tells it not to pad. The difference between the function versions is the return type: Format returns a Variant (String), while Format$ returns an actual String.

爱冒险 2024-11-10 13:16:12

最容易预先计算最大值,然后再次循环并填充;

Dim nums() As String: nums = Split("4,12,534,9999", ",")
Dim i As Long
Dim max As Long

For i = 0 To UBound(nums)
    If (Len(nums(i)) > max) Then max = Len(nums(i))
Next

For i = 0 To UBound(nums)
    nums(i) = String(max - Len(nums(i)), "0") & nums(i)
    Debug.Print nums(i)
Next

Easiest to precompute the max then loop again and pad;

Dim nums() As String: nums = Split("4,12,534,9999", ",")
Dim i As Long
Dim max As Long

For i = 0 To UBound(nums)
    If (Len(nums(i)) > max) Then max = Len(nums(i))
Next

For i = 0 To UBound(nums)
    nums(i) = String(max - Len(nums(i)), "0") & nums(i)
    Debug.Print nums(i)
Next
或十年 2024-11-10 13:16:12

我不确定为什么简单的字符串操作不起作用。

Select Case Len(folderstring)
  Case 1
    folderstring = "00" & folderstring
  Case 2
    folderstring = "0" & folderstring
  Case Else
    ' Do nothing here
End Case

或者

Dim zeroarray(1 To 3) As Variant

zeroarray = Array("00","0","")
folderstring = zeroarray(Len(folderstring)) & folderstring

I'm not sure why a simple string operation won't work out.

Select Case Len(folderstring)
  Case 1
    folderstring = "00" & folderstring
  Case 2
    folderstring = "0" & folderstring
  Case Else
    ' Do nothing here
End Case

OR

Dim zeroarray(1 To 3) As Variant

zeroarray = Array("00","0","")
folderstring = zeroarray(Len(folderstring)) & folderstring
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文